﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SYcwpb.Models;
using SYcwpb.Commands;
using System.Windows.Input;
using SYcwpb.Helpers;
using SYcwpb.Views;
using System.Collections.ObjectModel;
using SYcwpb.Controls;
using SYcwpb.Access;
using System.Data;
using System.Collections;
using System.Windows;



namespace SYcwpb.ViewModels
{
    public class DriverTeamViewModel : ViewModelBase
    {
        private int line = Convert.ToInt32(CONSTDATA.UserModel.Line);

        private DriverTeamAccess _teamAccess;
        private SqlDataLayer sqlHelper = new SqlDataLayer();

        /// <summary>
        /// 今天是否已将交路表的信息刷新到DriverCombine表
        /// </summary>
        private bool HasRefreshCrossRoad = false;

        private string _zbteam = "电客车xx组";
        private string _ybteam = "电客车xx组";
        private string _bbteam = "电客车xx组";
        private string _xbteam = "电客车xx组";

        private ICommand _combineViewComand;
        private ICommand _turnGroupsCommand;
        private ICommand _dutyNumCycleCommand;
        private ICommand _refreshCrossRoadCommand;
        private ICommand _turnGroupsByMonthCommand;
        private ICommand _replaceCommand;
        private ObservableCollection<DriverCard> _cardsCollectionsZB;
        private ObservableCollection<DriverCard> _cardsCollectionsBB;
        private ObservableCollection<DriverCard> _cardsCollectionsYB;
        private ObservableCollection<DriverCard> _cardsCollectionsXB;
        private ObservableCollection<DriverCard> _cardsCollectionsLeft;

        /// <summary>
        /// LastTurnTime   最晚轮换时间
        /// SwitchTimeZB   早班可调班的最晚时间
        /// SwitchTimeBB   白班可调班的最晚时间
        /// SwitchTimeYB   夜班可调班的最晚时间
        /// </summary>
        private Dictionary<string, string> ConfigInfo = new Dictionary<string, string>();
        /// <summary>
        /// 每张时刻表对应的交路
        /// </summary>
        Hashtable hstTimeTableWithCrossingRoad = new Hashtable();
        public ObservableCollection<DriverCard> ChangeCardsCollections { get; set; }



        /// <summary>
        /// 每天对应的时刻表
        /// </summary>
        Dictionary<string, string> hstTimeTableNameWithDate = new Dictionary<string, string>();

        private Dictionary<int, Driver> DicDriverInfo = new Dictionary<int, Driver>();

        #region 班组对应的电客车司机组字段的get；set

        public string ZBTeam
        {
            get { return _zbteam; }
            set
            {
                _zbteam = value;
                OnPropertyChanged("ZBTeam");
            }
        }

        public string YBTeam
        {
            get { return _ybteam; }
            set
            {
                _ybteam = value;
                OnPropertyChanged("YBTeam");
            }
        }

        public string BBTeam
        {
            get { return _bbteam; }
            set
            {
                _bbteam = value;
                OnPropertyChanged("BBTeam");
            }
        }

        public string XBTeam
        {
            get { return _xbteam; }
            set
            {
                _xbteam = value;
                OnPropertyChanged("XBTeam");
            }
        }
        #endregion

        #region 电客车司机组的司机铭牌集合 get;set;

        public ObservableCollection<DriverCard> CardsCollectionsZB
        {
            get
            {
                return _cardsCollectionsZB;
            }
            set
            {
                _cardsCollectionsZB = value;
                OnPropertyChanged("CardsCollectionsZB");
            }
        }

        private DriverCard _souceCard;
        public DriverCard SourceCard
        {
            get
            {
                return _souceCard;
            }
            set
            {
                _souceCard = value;
                OnPropertyChanged("SourceCard");
            }
        }

        public ObservableCollection<DriverCard> CardsCollectionsBB
        {
            get
            {
                return _cardsCollectionsBB;
            }
            set
            {
                _cardsCollectionsBB = value;
                OnPropertyChanged("CardsCollectionsBB");
            }
        }

        public ObservableCollection<DriverCard> CardsCollectionsYB
        {
            get
            {
                return _cardsCollectionsYB;
            }
            set
            {
                _cardsCollectionsYB = value;
                OnPropertyChanged("CardsCollectionsYB");
            }
        }

        public ObservableCollection<DriverCard> CardsCollectionsXB
        {
            get
            {
                return _cardsCollectionsXB;
            }
            set
            {
                _cardsCollectionsXB = value;
                OnPropertyChanged("CardsCollectionsXB");
            }
        }

        public ObservableCollection<DriverCard> CardsCollectionsLeft
        {
            get
            {
                return _cardsCollectionsLeft;
            }
            set
            {
                _cardsCollectionsLeft = value;
                OnPropertyChanged("CardsCollectionsLeft");
            }
        }

        #endregion

        private bool _isMutiRoadAdd;
        public bool IsMutiRoadAdd
        {
            get { return _isMutiRoadAdd; }
            set { _isMutiRoadAdd = value; }
        }


        public bool isOk { get; set; }

        private string _endDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
        public string EndDate
        {
            get { return _endDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_endDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _endDate = curT.ToString("yyyy-MM-dd");

                OnPropertyChanged("EndDate");
            }
        }
        private string _startDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
        public string StartDate
        {
            get { return _startDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_startDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _startDate = curT.ToString("yyyy-MM-dd");

                OnPropertyChanged("StartDate");
            }
        }

        private bool _isKeepSwr = true;
        public bool IsKeepSwr
        {
            get { return _isKeepSwr; }
            set
            {
                _isKeepSwr = value;
                OnPropertyChanged("IsKeepSwr");
            }
        }
        private string _selectedDate;
        public string SelectedDate
        {
            get { return _selectedDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_selectedDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _selectedDate = curT.ToString("yyyy-MM-dd");

                OnPropertyChanged("SelectedDate");
            }
        }

        private string _selectedEndDate;
        public string SelectedEndDate
        {
            get { return _selectedEndDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_selectedEndDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _selectedEndDate = curT.ToString("yyyy-MM-dd");

                OnPropertyChanged("SelectedEndDate");
            }
        }
        #region Command 集合

        public ICommand CombineViewComand
        {
            get
            {
                if (null == _combineViewComand)
                    _combineViewComand = new RelayCommands(para => this.OpenCombineView());
                return _combineViewComand;
            }
        }

        public ICommand TurnGroupsCommand
        {
            get
            {
                if (null == _turnGroupsCommand)
                {
                    _turnGroupsCommand = new RelayCommands(para => this.TurnGroups());
                }
                return _turnGroupsCommand;
            }
        }

        public ICommand DutyNumCycleCommand
        {
            get
            {
                if (null == _dutyNumCycleCommand)
                {
                    _dutyNumCycleCommand = new RelayCommands(para => this.DutyNumCycle());
                }
                return _dutyNumCycleCommand;
            }
        }

        public ICommand RefreshCrossRoadCommand
        {
            get
            {
                if (null == _refreshCrossRoadCommand)
                {
                    _refreshCrossRoadCommand = new RelayCommands(para => this.RefreshCrossRoadMethod());
                }
                return _refreshCrossRoadCommand;
            }
        }

        public ICommand TurnGroupsByMonthCommand
        {
            get
            {
                if (null == _turnGroupsByMonthCommand)
                {
                    _turnGroupsByMonthCommand = new RelayCommands(para => this.TurnGroupsByMonthPlane());
                }
                return _turnGroupsByMonthCommand;
            }
        }

        public ICommand ReplaceCommand
        {
            get
            {
                if (null == _replaceCommand)
                {
                    _replaceCommand = new RelayCommands(para => this.Replace());
                }
                return _replaceCommand;
            }
        }
        #endregion

        private void OpenCombineView()
        {
            DriverCombineView.GetInstance().Show();
        }

        private void InitChangeCards()
        {
            ChangeCardsCollections = new ObservableCollection<DriverCard>();
            ChangeCardsCollections.Add(new DriverCard());
            ChangeCardsCollections.Add(new DriverCard());
            ChangeCardsCollections[0].Slimming();
            ChangeCardsCollections[0].Height = 67;
            ChangeCardsCollections[1].Slimming();
            ChangeCardsCollections[1].Height = 67;
        }
        public DriverTeamViewModel()
        {
            try
            {
                _teamAccess = new DriverTeamAccess(line);

                _teamAccess.GetConfig(ref ConfigInfo);

                InitTeamText();
                InitChangeCards();
                InitCardsCollections();

                HasRefreshCrossRoad = _teamAccess.CheckHasRefreshCrossRoad();
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }

        }

        private void InitTeamText()
        {
            DataTable groupToTeamDT = _teamAccess.GetGroupToTeam();
            if (groupToTeamDT == null || groupToTeamDT.Rows.Count != 4)
                return;
            for (int i = 0; i < 4; i++)
            {
                string _class = groupToTeamDT.Rows[i]["zbyx"].ToString();
                string team = groupToTeamDT.Rows[i]["team"].ToString();
                switch (_class)
                {
                    case "0":
                        ZBTeam = GetTeamString(team);
                        break;
                    case "1":
                        XBTeam = GetTeamString(team);
                        break;
                    case "2":
                        BBTeam = GetTeamString(team);
                        break;
                    case "3":
                        YBTeam = GetTeamString(team);
                        break;
                }
            }
        }



        /// <summary>
        /// 获取司机责任
        /// </summary>
        /// <returns></returns>
        public DataRow GetDrDriverDuty(string useid)
        {
            string strsql = "select ID , duty , userid from DriverCombine unpivot (userid for duty in([dcom_opdriver] , [dcom_monidriver],[dcom_monidriverTwo])) t where dcom_date='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and dcom_lineid='" + line + "'";
            DataTable dtDuty = sqlHelper.SelectDt(strsql);
            DataRow[] drDuty = dtDuty.Select("userid='" + useid + "'");
            if (drDuty.Length > 0)
            {
                return drDuty[0];
            }
            return null;


        }
        public void InitCardsCollections(string tranId)
        {


            DataTable driverDt = _teamAccess.GetDriverInfo(tranId);
            string filter = "cls_id = 0";
            CardsCollectionsZB = GetCardsByTable(filter, driverDt);

            filter = "cls_id = 2";
            CardsCollectionsBB = GetCardsByTable(filter, driverDt);

            filter = "cls_id = 3";
            CardsCollectionsYB = GetCardsByTable(filter, driverDt);

            filter = "cls_id = 1";
            CardsCollectionsXB = GetCardsByTable(filter, driverDt);

            //查找休班的user_id
            DataTable dtRest = _teamAccess.GetDriverInfoByRest(tranId);



            filter = "1=1";
            CardsCollectionsLeft = GetCardsByTable(filter, dtRest);

        }
        public void InitCardsCollections()
        {

            InitCardsCollections(null);
        }

        private ObservableCollection<DriverCard> GetCardsByTable(string filter, DataTable dt)
        {
            ObservableCollection<DriverCard> Temp = new ObservableCollection<DriverCard>();

            DataRow[] result = dt.Select(filter);
            for (int i = 0; i < result.Length; i++)
            {
                DriverCard card = new DriverCard();

                card.Driverid = result[i]["user_id"].ToString();
                card.JobNum = result[i]["jobNum"].ToString();
                card.DriverName = result[i]["user_name"].ToString();
                card.ReplaceName = result[i]["replace_name"].ToString();
                card.DutyNum = result[i]["duty_num"].ToString();
                card.CrossNum = result[i]["cr_num"].ToString();
                card.DType = result[i]["grp_type"].ToString();
                card.Driver_group = result[i]["cls_id"].ToString();
                card.DutyNO = result[i]["dcom_NO"].ToString();
                card.ReplaceDriverId = result[i]["replaceDriver"].ToString();
                card.DriverGroupId = Convert.ToInt32(result[i]["id"]);

                Temp.Add(card);
            }
            return Temp;
        }

        private void DutyNumCycle()
        {
            string today = DateTime.Now.ToString("yyyy-MM-dd");
            string fourdaysago = DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd");
            string turnDate = null; //应该执行更新的日期

            string lastUpdate = _teamAccess.GetLastNumCycleDay();

            bool canUpdate = true;

            if (!string.IsNullOrEmpty(lastUpdate))
            {
                turnDate = DateTime.Parse(lastUpdate).AddDays(4).ToString("yyyy-MM-dd");
                if (turnDate.CompareTo(today) > -1)  //如果当前日期小于等于应该执行更新的日期，则不用更新
                {
                    canUpdate = false;
                }
            }

            if (!canUpdate)
            {
                MessageBoxHelper.ShowTips(string.Format("编号循环应为四天执行一次，当前日期为{0},上次执行更新时间为{1},请确认！", today, lastUpdate));
                return;
            }

            string lastTurntime = null;
            if (!ConfigInfo.TryGetValue("LastTurnTime", out lastTurntime))
                lastTurntime = "03:00:00"; //如果获取失败就使用默认时间

            if (DateTime.Now.TimeOfDay.ToString().CompareTo(lastTurntime) >= 0)  //在最晚时间前才可以执行
            {
                MessageBoxHelper.ShowError(string.Format("根据当前设置，编号循环时间限于{0}前！", lastTurntime));
                return;
            }

            //如果不同意更新则返回
            if (string.IsNullOrEmpty(lastUpdate))   //如果是从来没有执行过更新的
            {
                if (!MessageBoxHelper.ConfirmYesNo(string.Format("检测到系统从未执行过编号循环，确定要执行此次操作吗？")))
                    return;
            }
            else if (!MessageBoxHelper.ConfirmYesNo(string.Format("编号循环为应为四天执行一次！\n上次执行日期为：{0}，应执行日期为：{1},当前日期为：{2}，确定要执行更新吗？", lastUpdate, turnDate, today)))
                return;

            if (!_teamAccess.ExeNumCycle())  //如果执行更新循环失败
            {
                MessageBoxHelper.ShowError("执行编号循环时出现异常！请确认后重试");
                return;
            }

            //成功执行编号循环后添加记录到 ReNumRecord表
            _teamAccess.AddNumCycleRecord();
        }

        private void TurnGroups()
        {
            if (_teamAccess.CheckHasTurn())
            {
                MessageBoxHelper.ShowError("每天只能执行一次班组轮换，请确认！");
                return;
            }

            if (!MessageBoxHelper.ConfirmYesNo("确定要进行今天的班组轮换吗？"))
                return;

            string lastTurntime = null;
            if (!ConfigInfo.TryGetValue("LastTurnTime", out lastTurntime))
                lastTurntime = "03:00:00"; //如果获取失败就使用默认时间

            if (DateTime.Now.TimeOfDay.ToString().CompareTo(lastTurntime) >= 0)  //在最晚时间前才可以执行轮换
            {
                MessageBoxHelper.ShowError(string.Format("根据当前设置，每天轮班限于{0}前！", lastTurntime));
                return;
            }

            AddDriverAttendRecord();

            //执行编号循环
            DutyNumCycle();

            if (ExeTurnGroups())
            {
                AddCrossRoadInfo();

                InitCardsCollections();

                InitTeamText();
            }
        }

        /// <summary>
        /// 执行司机班组轮换，并添加记录到ReTurnRecord表
        /// </summary>
        private bool ExeTurnGroups()
        {
            string error = "";
            if (!_teamAccess.ExeTurnGroups(ref error))
            {
                MessageBoxHelper.ShowError(error);
                return false;
            }

            return _teamAccess.AddTrunGroupsRecord();
        }

        /// <summary>
        /// 保存昨日司机的出勤记录
        /// </summary>
        private void AddDriverAttendRecord()
        {
            if (!_teamAccess.AddAttenRecord())
            {
                MessageBoxHelper.ShowError("保存昨日司机出勤记录失败，请在司机公里数、工时统计处增加昨天记录！");
            }
        }

        /// <summary>
        /// 加载今日的CrossingRoad表信息出勤信息到DriverCombine表
        /// </summary>
        private bool AddCrossRoadInfo()
        {
            if (!_teamAccess.CheckHasTurn())
            {
                MessageBoxHelper.ShowError("今天尚没进行轮班，不能执行安排交路到司机，请确认！");
                return false;
            }

            int tableID = -1;
            string tableName = "";
            if (!_teamAccess.CheckHasTimeTableToDate(ref tableID, ref tableName, DateTime.Now.ToString("yyyy-MM-dd")))
            {
                MessageBoxHelper.ShowError("没有给今天配置出勤时刻表。请点击主界面“安排时刻表到日期”进行配置！");
                return false;
            }

            if (!_teamAccess.CheckHasCrossRoad(tableID))
            {
                MessageBoxHelper.ShowError(string.Format("找不到时刻表：{0} 的交路表，请执行【生成出勤表】功能并保存！", tableName));
                return false;
            }

            //这里要多加一个多次按排交路到司机的条件
            if (HasRefreshCrossRoad && !_isMutiRoadAdd)
            {
                MessageBoxHelper.ShowError("今天已经执行过安排交路到司机！");
                return false;
            }

            string err = null;
            if (_teamAccess.RefreshCrossingRoad(tableID, tableName, ref err)) //如果更新成功
            {
                if (!HasRefreshCrossRoad)          //如果没添加记录就添加进去
                {
                    _teamAccess.AddRecordToRefreshCrossRoad();
                    this.HasRefreshCrossRoad = true;
                }
            }
            else
            { MessageBoxHelper.ShowError(string.Format("执行交路到司机操作时出现异常：{0}", err)); return false; }

            return true;
        }

        private void RefreshCrossRoadMethod()
        {
            if (this.AddCrossRoadInfo())
                InitCardsCollections();
        }

        private string GetTeamString(string teamID)
        {
            string result = "";
            switch (teamID)
            {
                case "1":
                    result = "电客车一组";
                    break;
                case "2":
                    result = "电客车二组";
                    break;
                case "3":
                    result = "电客车三组";
                    break;
                case "4":
                    result = "电客车四组";
                    break;
            }
            return result;
        }

        private int GetTeamInt(string teamName)
        {
            int teamID = -1;
            switch (teamName)
            {
                case "电客车一组":
                    teamID = 1;
                    break;
                case "电客车二组":
                    teamID = 2;
                    break;
                case "电客车三组":
                    teamID = 3;
                    break;
                case "电客车四组":
                    teamID = 4;
                    break;
            }
            return teamID;
        }

        public bool ExchangeGroups(string team1, string team2, ref string error)
        {
            int intT1 = GetTeamInt(team1);
            int intT2 = GetTeamInt(team2);
            if (intT1 == -1 || intT2 == -1)
            {
                error = "无法解析当前班组对应ID";
                return false;
            }
            int class1 = _teamAccess.GetGroupByTeamID(intT1);
            int class2 = _teamAccess.GetGroupByTeamID(intT2);

            if (class1 == -1 || class2 == -1)
            {
                error = "获取当前电客车司机司机组对应的出勤班组失败！";
                return false;
            }
            if (_teamAccess.ExangeClass(intT1, class1, intT2, class2))
            {
                if (!AddCrossRoadInfo())
                {
                    error = "当前更新司机的交路信息时出现异常，请检查无误后执行【安排交路到司机】以确保当天出勤信息准确";
                }

                InitCardsCollections();
            }
            return true;
        }


        #region 周月计划排班表所用代码
        #region 主函数
        private void TurnGroupsByMonthPlane()
        {
            try
            {
                //判断是否有班次信息 没有的话进行初始化
                DataTable dtIniTrueClas = _teamAccess.GetLastClass();
                if (dtIniTrueClas.Rows.Count != 4)
                {
                    InitializationClass iniclass = new InitializationClass(line.ToString());
                    iniclass.ShowDialog();
                }

                MonthPlaneDate m = new MonthPlaneDate(this);
                m.ShowDialog();
                if (isOk == false)
                {
                    return;
                }
                // MessageBoxHelper.ShowError("你好");
                //设置这个月时刻表对应的所以交路
                int year = DateTime.Now.Year;
                int month = DateTime.Now.Month;
                //判断是否已经生成下个月的计划表
                //DataTable dtHistoryNextMonth = _teamAccess.GetClassTurnPlaneRecord(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);
                //if (dtHistoryNextMonth.Rows.Count > 0)
                //{
                //    MessageBoxHelper.ShowError("下个月的计划表已经生成,无法再执行轮班计划");

                //    return;
                //}
                //DataTable dtHistoryThisMonth = _teamAccess.GetClassTurnPlaneRecord(DateTime.Now.Year, DateTime.Now.Month);
                //if (dtHistoryThisMonth.Rows.Count == 0)
                //{
                //    //判断是否生成下个月的计划
                //    year = DateTime.Now.Year;
                //    month = DateTime.Now.Month;
                //    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("取消生成当月月排班表");
                //}
                //else
                //{
                //    MessageBoxResult result = MessageBoxHelper.ShowYesNoAndTips("是否生成下个月的计划表");
                //    if (result == MessageBoxResult.Yes)
                //    {
                //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("生成下个月排班表");
                //        year = DateTime.Now.AddMonths(1).Year;
                //        month = DateTime.Now.AddMonths(1).Month;
                //    }
                //    else
                //    {
                //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("取消生成下个月排班表");
                //        return;
                //    }
                //}


                List<string> lstNoSetTimeTable = GetNoSetTimeTable(SelectedDate, SelectedEndDate);
                if (lstNoSetTimeTable.Count > 0)
                {
                    lstNoSetTimeTable.Insert(0, "请设置先设置以下日期排班表:" + Environment.NewLine);
                    MessageBoxHelper.ShowError(lstNoSetTimeTable);
                    return;
                }
                SetTimeTableWithCrossingRoad(SelectedDate, SelectedEndDate);
                List<string> lstDriver = CheckHasDriverEnoughInCrossingRoad();
                if (lstDriver.Count > 0)
                {
                    lstDriver.Insert(0, "司机与交路信息不符，是否继续轮班?");
                    MessageBoxResult msr = MessageBoxHelper.ShowYesNoAndTips(lstDriver);
                    if (msr == MessageBoxResult.Yes)
                    { }
                    else
                    {
                        return;
                    }
                }
                DataTable dtSwr = _teamAccess.GetSwitchRecordByMonth(Convert.ToDateTime(SelectedDate).AddDays(-1).ToString("yyyy-MM-dd"), SelectedEndDate);
                DataRow[] drsCancelBack = dtSwr.Select("sr_chgdate>'" + SelectedEndDate + "' and sr_appdate<'" + Convert.ToDateTime(SelectedDate).AddDays(-1).ToString("yyyy-MM-dd") + "'");
                DataRow[] drsCancelAll = dtSwr.Select("sr_appdate>='" + Convert.ToDateTime(SelectedDate).AddDays(-1).ToString("yyyy-MM-dd") + "' and sr_appdate<='" + SelectedEndDate + "'");
                //查找出需要取消调班的

                //提示有哪些调班记录会被取消还班
                List<string> al = new List<string>();
                foreach (DataRow drSwr in drsCancelBack)
                {
                    al.Add(drSwr["appUserName"].ToString() + "与" + drSwr["chagUserName"].ToString() + " " + drSwr["sr_chgdate"].ToString() + "的还班记录将被取消");
                }
                foreach (DataRow drSwr in drsCancelAll)
                {
                    if (!string.IsNullOrEmpty(drSwr["sr_chgdate"].ToString()))
                    {
                        if (Convert.ToDateTime(drSwr["sr_chgdate"].ToString()) > Convert.ToDateTime(SelectedEndDate))
                        {
                            al.Add(drSwr["appUserName"].ToString() + "与" + drSwr["chagUserName"].ToString() + " " + drSwr["sr_chgdate"].ToString() + "的还班记录将被取消");
                        }
                    }
                }

                if (al.Count > 0)
                {
                    al.Insert(0, "以下调班将被取消还班");
                    MessageBoxResult msr = MessageBoxHelper.ShowYesNoAndTips(al);
                    if (msr == MessageBoxResult.Yes)
                    { }
                    else
                    {
                        return;
                    }
                }
                if (IsKeepSwr)
                {
                    List<string> alist = new List<string>();
                    DataTable dtDel = _teamAccess.GetSwitchRecordByDel(SelectedEndDate);
                    if (dtDel.Rows.Count > 0)
                    {
                        alist.Add("以下" + SelectedEndDate.ToString() + "后的调班将被取消");
                        foreach (DataRow dr in dtDel.Rows)
                        {
                            alist.Add(dr["appUserName"].ToString() + "与" + dr["chagUserName"].ToString() + " " + dr["sr_appdate"].ToString() + "的调班记录将被取消");
                        }
                    }

                    if (alist.Count > 0)
                    {
                        alist.Insert(0, "以下调班将被取消还班");
                        MessageBoxResult msr = MessageBoxHelper.ShowYesNoAndTips(alist);
                        if (msr == MessageBoxResult.Yes)
                        { }
                        else
                        {
                            return;
                        }
                    }
                }

                //lstDriver = CheckHasDriverEnoughInStationCrossingRoad();
                //if (lstDriver.Count > 0)
                //{
                //    MessageBoxHelper.ShowError(lstDriver);
                //    return;
                //}
                //把交路分配给司机组
                InitAllDriver();
                if (SetCrossingRoadToDriver(SelectedDate, SelectedEndDate))
                {
                    MessageBoxHelper.ShowTips("轮班成功！");
                    sqlHelper.ExecuteSql("insert into AdjustDcReturnRecord(id,recordDate,lineid,adr_user,action_type) values(newid(),getdate()," + CONSTDATA.UserModel.Line + "," + CONSTDATA.UserModel.ID + ",'重新轮班');");
                }
                else
                {
                    MessageBoxHelper.ShowTips("轮班失败!");
                }
            }
            catch (Exception ex)
            {

                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
                MessageBoxHelper.ShowError("轮班失败" + ex.Message);
            }


        }
        #endregion
        #region 查询是否符合排班要求

        /// <summary>
        /// 获取没有设置时刻表的日期
        /// </summary>
        /// <returns></returns>
        public List<string> GetNoSetTimeTable(int year, int month)
        {
            hstTimeTableNameWithDate.Clear();
            List<string> lstNoSetDay = new List<string>();
            //获取这一整个月的排班表信息
            DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimetable(year, month);
            int daysInMonth = DateTime.DaysInMonth(year, month);

            for (int i = 1; i <= daysInMonth; i++)
            {
                //查找数据库看这一天有没有设置排班排班表
                string fiter = "AssignDate=" + "'" + year.ToString() + "-" + month.ToString().PadLeft(2, '0') + "-" + i.ToString().PadLeft(2, '0') + "'"; //筛选条件
                string days = year.ToString() + "-" + month.ToString().PadLeft(2, '0') + "-" + i.ToString().PadLeft(2, '0');
                DataRow[] drs = dtMonthTimeTable.Select(fiter);
                if (drs.Length == 0)
                {
                    lstNoSetDay.Add(days);
                }
                else
                {
                    //获取每天对应的交路表
                    hstTimeTableNameWithDate.Add(days, drs[0][1].ToString());
                }
            }

            return lstNoSetDay;
        }

        /// <summary>
        /// 获取没有设置时刻表的日期并设置时刻表与日期的关系
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public List<string> GetNoSetTimeTable(string startDay, string endDay)
        {
            hstTimeTableNameWithDate.Clear();
            List<string> lstNoSetDay = new List<string>();
            //获取这一整个月的排班表信息
            DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimetable(startDay, endDay);
            // int daysInMonth = DateTime.DaysInMonth(year, month);
            DateTime dtStart = Convert.ToDateTime(startDay);
            DateTime dtend = Convert.ToDateTime(endDay);
            DateTime dtTemp = dtStart;

            while (dtTemp <= dtend)
            {
                string fiter = "AssignDate=" + "'" + dtTemp.Year.ToString() + "-" + dtTemp.Month.ToString().PadLeft(2, '0') + "-" + dtTemp.Day.ToString().PadLeft(2, '0') + "'"; //筛选条件
                string days = dtTemp.Year.ToString() + "-" + dtTemp.Month.ToString().PadLeft(2, '0') + "-" + dtTemp.Day.ToString().PadLeft(2, '0');
                DataRow[] drs = dtMonthTimeTable.Select(fiter);
                if (drs.Length == 0)
                {
                    lstNoSetDay.Add(days);
                }
                else
                {
                    //获取每天对应的交路表
                    hstTimeTableNameWithDate.Add(days, drs[0][1].ToString());
                }
                dtTemp = dtTemp.AddDays(1);

            }

            return lstNoSetDay;
        }

        /// <summary>
        /// 判断司机是否满足给交路分配
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public List<string> CheckHasDriverEnoughInCrossingRoad()
        {
            List<string> lstDriver = new List<string>();
            DataTable dtDriverCountByTeam = GetDriverCountByTeam();
            foreach (DictionaryEntry de in hstTimeTableWithCrossingRoad)
            {
                DataTable dtCrossingRoad = (DataTable)de.Value;
                if (dtCrossingRoad == null || dtCrossingRoad.Rows.Count == 0)
                    throw new Exception(" " + de.Key + "没有交路");

                DataRow[] drZB = dtCrossingRoad.Select("zby=0");
                DataRow[] drBB = dtCrossingRoad.Select("zby=2");
                DataRow[] drYB = dtCrossingRoad.Select("zby=3");

                CheackListDriverByTeam(drZB, dtDriverCountByTeam, "1", ref lstDriver, de.Key.ToString(), "0");
                CheackListDriverByTeam(drBB, dtDriverCountByTeam, "1", ref lstDriver, de.Key.ToString(), "2");
                CheackListDriverByTeam(drYB, dtDriverCountByTeam, "1", ref lstDriver, de.Key.ToString(), "3");
                CheackListDriverByTeam(drZB, dtDriverCountByTeam, "2", ref lstDriver, de.Key.ToString(), "0");
                CheackListDriverByTeam(drBB, dtDriverCountByTeam, "2", ref lstDriver, de.Key.ToString(), "2");
                CheackListDriverByTeam(drYB, dtDriverCountByTeam, "2", ref lstDriver, de.Key.ToString(), "3");
                CheackListDriverByTeam(drZB, dtDriverCountByTeam, "3", ref lstDriver, de.Key.ToString(), "0");
                CheackListDriverByTeam(drBB, dtDriverCountByTeam, "3", ref lstDriver, de.Key.ToString(), "2");
                CheackListDriverByTeam(drYB, dtDriverCountByTeam, "3", ref lstDriver, de.Key.ToString(), "3");
                CheackListDriverByTeam(drZB, dtDriverCountByTeam, "4", ref lstDriver, de.Key.ToString(), "0");
                CheackListDriverByTeam(drBB, dtDriverCountByTeam, "4", ref lstDriver, de.Key.ToString(), "2");
                CheackListDriverByTeam(drYB, dtDriverCountByTeam, "4", ref lstDriver, de.Key.ToString(), "3");
                //判断交路是否符合司机数
                //foreach (DataRow dr in dtDriverCountByTeam.Rows)
                //{
                //    if (Convert.ToInt32(dr[1].ToString()) < drZB.Length)
                //    {
                //        lstDriver.Add(GetTeamString(dr[0].ToString()) + "的人数少于时刻表" + de.Key + "的早班交路");
                //    }
                //    if (Convert.ToInt32(dr[1].ToString()) < drBB.Length)
                //    {
                //        lstDriver.Add(GetTeamString(dr[0].ToString()) + "的人数少于时刻表" + de.Key + "的白班交路");
                //    }
                //    if (Convert.ToInt32(dr[1].ToString()) < drYB.Length)
                //    {
                //        lstDriver.Add(GetTeamString(dr[0].ToString()) + "的人数少于时刻表" + de.Key + "的晚班交路");
                //    }
                //}
            }
            return lstDriver;
        }

        public void CheackListDriverByTeam(DataRow[] drsTeam, DataTable dtDriverCountByTeam, string line, ref List<string> lst, string tbl, string zby)
        {


            DataTable dtTeam = drsTeam.CopyToDataTable();
            DataRow[] drZXCross = dtTeam.Select("grp_id=5");
            DataRow[] drSCXCross = dtTeam.Select("grp_id=3");
            DataRow[] drDCCross = dtTeam.Select("grp_id=2");
            DataRow[] drYBBCross = dtTeam.Select("grp_id=6");
            DataRow[] drBBCross = dtTeam.Select("grp_id=4");
            DataRow[] drRBCross = dtTeam.Select("grp_id=1");
            int zxNum = 0;
            int scxnum = 0;
            int dcnum = 0;
            int bbnum = 0;
            int rbnum = 0;
            int ybbnum = 0;

            DataRow[] drZXDriver = dtDriverCountByTeam.Select("dcom_grp_type=5 and dcom_team='" + line + "' ");
            if (drZXDriver.Length > 0)
            {
                zxNum = Convert.ToInt32(drZXDriver[0]["num"].ToString());
            }
            DataRow[] drSCXDriver = dtDriverCountByTeam.Select("dcom_grp_type=3 and dcom_team='" + line + "' ");
            if (drSCXDriver.Length > 0)
            {
                scxnum = Convert.ToInt32(drSCXDriver[0]["num"].ToString());
            }
            DataRow[] drDCDriver = dtDriverCountByTeam.Select("dcom_grp_type=2 and dcom_team='" + line + "' ");
            if (drDCDriver.Length > 0)
            {
                dcnum = Convert.ToInt32(drDCDriver[0]["num"].ToString());
            }
            DataRow[] drYBBDriver = dtDriverCountByTeam.Select("dcom_grp_type=6 and dcom_team='" + line + "' ");
            if (drYBBDriver.Length > 0)
            {
                ybbnum = Convert.ToInt32(drYBBDriver[0]["num"].ToString());
            }
            DataRow[] drBBDriver = dtDriverCountByTeam.Select("dcom_grp_type=4 and dcom_team='" + line + "' ");
            if (drBBDriver.Length > 0)
            {
                bbnum = Convert.ToInt32(drBBDriver[0]["num"].ToString());
            }
            DataRow[] drRBDriver = dtDriverCountByTeam.Select("dcom_grp_type=1 and dcom_team='" + line + "' ");
            if (drRBDriver.Length > 0)
            {
                rbnum = Convert.ToInt32(drRBDriver[0]["num"].ToString());
            }
            if (zby == "0")
            {
                zby = "早班";

                zxNum = zxNum + scxnum + dcnum + bbnum + rbnum + ybbnum - drSCXCross.Length - drDCCross.Length - drYBBCross.Length - drBBCross.Length - drRBCross.Length;

            }
            else if (zby == "2")
            {
                zby = "白班";
            }
            else
            {
                zby = "晚班";
            }

            if (drZXCross.Length > zxNum)
            {
                lst.Add(GetTeamString(line) + "的正线司机人数少于时刻表" + tbl + "的" + zby + "交路");
            }
            if (drSCXCross.Length > scxnum)
            {
                lst.Add(GetTeamString(line) + "的试车线司机人数少于时刻表" + tbl + "的" + zby + "交路");
            }
            if (drDCCross.Length > dcnum)
            {
                lst.Add(GetTeamString(line) + "的调车司机人数少于时刻表" + tbl + "的" + zby + "交路");
            }
            if (drYBBCross.Length > ybbnum)
            {
                lst.Add(GetTeamString(line) + "的月备班司机人数少于时刻表" + tbl + "" + zby + "的交路");
            }
            if (drBBCross.Length > bbnum)
            {
                lst.Add(GetTeamString(line) + "的备班司机人数少于时刻表" + tbl + "的" + zby + "交路");
            }
            if (drRBCross.Length > rbnum)
            {
                lst.Add(GetTeamString(line) + "的热备司机人数少于时刻表" + tbl + "的" + zby + "交路");
            }



        }

        /// <summary>
        /// 判断是否设置了车场司机
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public List<string> CheckHasDriverEnoughInStationCrossingRoad()
        {
            List<string> lstDriver = new List<string>();
            //获取所有组的司机
            DataTable dtDriver = _teamAccess.GetDtDriverCombine();
            //获取四个组非正线司机的信息
            //DataRow[] drOne = dtDriver.Select("dcom_grp_type<>5 and dcom_team=1");
            //DataRow[] drTwo = dtDriver.Select("dcom_grp_type<>5 and dcom_team=2");
            //DataRow[] drThree = dtDriver.Select("dcom_grp_type<>5 and dcom_team=3");
            //DataRow[] drFour = dtDriver.Select("dcom_grp_type<>5 and dcom_team=4");
            foreach (DictionaryEntry de in hstTimeTableWithCrossingRoad)
            {
                DataTable dtCrossingRoad = (DataTable)de.Value;
                DataRow[] drZB = dtCrossingRoad.Select("zby=0 and grp_id<>5");
                DataRow[] drBB = dtCrossingRoad.Select("zby=2 and grp_id<>5");
                DataRow[] drYB = dtCrossingRoad.Select("zby=3 and grp_id<>5");
                //foreach (DataRow dr in drZB)
                //{
                //    DataRow[] drOne = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " dcom_team=1");
                //    SetErrorInfo(drOne,ref lstDriver, dr, de, dtCrossingRoad, "0", "1");
                //    //if (drOne.Length == 0)
                //    //{
                //    //    lstDriver.Add(GetTeamString("1") + "没有设置" + GetDriveType(dr["dcdr_driverType"].ToString())+"人员与交路表"+de.Key+"的交路信息不符合");
                //    //}
                //    //else
                //    //{
                //    //    //判断数量是否相同
                //    //    DataRow[] drNum = dtCrossingRoad.Select("zby=0 and dcdr_driverType=" + dr["dcdr_driverType"].ToString() + "");
                //    //    if (drOne.Length > drNum.Length)
                //    //    {
                //    //        lstDriver.Add(GetTeamString("1") + "设置的" + GetDriveType(dr["dcdr_driverType"].ToString()) + "人员多于交路表：" + de.Key + "的"+GetDriveType(dr["dcdr_driverType"].ToString())+"的人员");
                //    //    }
                //    //    else if (drOne.Length < drNum.Length)
                //    //    {
                //    //        lstDriver.Add(GetTeamString("1") + "设置的" + GetDriveType(dr["dcdr_driverType"].ToString()) + "人员少于交路表：" + de.Key + "的" + GetDriveType(dr["dcdr_driverType"].ToString()) + "的人员");
                //    //    }
                //    //}
                //    DataRow[] drTwo = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " dcom_team=2");
                //    SetErrorInfo(drOne, ref lstDriver, dr, de, dtCrossingRoad, "0", "2");
                //    DataRow[] drThree = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=3");
                //    SetErrorInfo(drOne, ref lstDriver, dr, de, dtCrossingRoad, "0", "3");
                //    DataRow[] drFour = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=4");
                //    SetErrorInfo(drOne, ref lstDriver, dr, de, dtCrossingRoad, "0", "4");
                //}
                setErrorInfo(drZB, dtDriver, "0", ref lstDriver, dtCrossingRoad, de);
                setErrorInfo(drBB, dtDriver, "2", ref lstDriver, dtCrossingRoad, de);
                setErrorInfo(drYB, dtDriver, "3", ref lstDriver, dtCrossingRoad, de);
                //foreach (DataRow dr in drBB
                //{
                //    DataRow[] drOne = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " dcom_team=1");
                //    DataRow[] drTwo = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " dcom_team=2");
                //    DataRow[] drThree = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=3");
                //    DataRow[] drFour = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " dcom_team=4");
                //}
                //foreach (DataRow dr in drYB)
                //{
                //    DataRow[] drOne = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=1");
                //    DataRow[] drTwo = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=2");
                //    DataRow[] drThree = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=3");
                //    DataRow[] drFour = dtDriver.Select("dcom_grp_type=" + dr["dcdr_driverType"].ToString() + " and dcom_team=4");
                //}


            }
            return lstDriver;
        }

        public void SetErrorInfo(DataRow[] drOne, ref List<string> lstDriver, DataRow dr, DictionaryEntry de, DataTable dtCrossingRoad, string zby, string team)
        {
            if (drOne.Length == 0)
            {
                lstDriver.Add(GetTeamString(team) + "没有设置" + GetDriveType(dr["grp_id"].ToString()) + "人员与交路表" + de.Key + "的" + GetZBYName(zby) + "交路信息不符合" + Environment.NewLine);
            }
            else
            {
                //判断数量是否相同
                DataRow[] drNum = dtCrossingRoad.Select("zby=" + zby + " and grp_id=" + dr["grp_id"].ToString() + "");
                if (drOne.Length > drNum.Length)
                {
                    lstDriver.Add(GetTeamString(team) + "设置的" + GetDriveType(dr["grp_id"].ToString()) + "人员多于交路表：" + de.Key + "的" + GetZBYName(zby) + "交路" + GetDriveType(dr["grp_id"].ToString()) + "人员" + Environment.NewLine);
                }
                else if (drOne.Length < drNum.Length)
                {
                    lstDriver.Add(GetTeamString(team) + "设置的" + GetDriveType(dr["grp_id"].ToString()) + "人员少于交路表：" + de.Key + "的" + GetZBYName(zby) + "交路的" + GetDriveType(dr["grp_id"].ToString()) + "人员" + Environment.NewLine);
                }
            }
        }

        public void setErrorInfo(DataRow[] drZB, DataTable dtDriver, string zby, ref List<string> lstDriver, DataTable dtCrossingRoad, DictionaryEntry de)
        {
            foreach (DataRow dr in drZB)
            {
                DataRow[] drOne = dtDriver.Select("dcom_grp_type=" + dr["grp_id"].ToString() + "and dcom_team=1");
                SetErrorInfo(drOne, ref lstDriver, dr, de, dtCrossingRoad, zby, "1");
                DataRow[] drTwo = dtDriver.Select("dcom_grp_type=" + dr["grp_id"].ToString() + "and dcom_team=2");
                SetErrorInfo(drTwo, ref lstDriver, dr, de, dtCrossingRoad, zby, "2");
                DataRow[] drThree = dtDriver.Select("dcom_grp_type=" + dr["grp_id"].ToString() + " and dcom_team=3");
                SetErrorInfo(drThree, ref lstDriver, dr, de, dtCrossingRoad, zby, "3");
                DataRow[] drFour = dtDriver.Select("dcom_grp_type=" + dr["grp_id"].ToString() + " and dcom_team=4");
                SetErrorInfo(drFour, ref lstDriver, dr, de, dtCrossingRoad, zby, "4");
            }
        }


        /// <summary>
        /// 获取每一组的人数
        /// </summary>
        /// <returns></returns>
        public DataTable GetDriverCountByTeam()
        {
            DataTable dtDriverCountByTeam = _teamAccess.GetDtDriverCountByTeam();
            return dtDriverCountByTeam;

        }

        /// <summary>
        /// 时刻表对应的交路
        /// </summary>
        /// <returns></returns>
        public void SetTimeTableWithCrossingRoad(int year, int month)
        {
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("获取时刻表对应交路");
            hstTimeTableWithCrossingRoad.Clear();
            // Hashtable hstTimeTableWithCrossingRoad = new Hashtable();
            DataTable dtTimeTableID = _teamAccess.GetDtMonthTimeTableId(year, month);

            foreach (DataRow dr in dtTimeTableID.Rows)
            {

                DataTable dtCrossingRoad = _teamAccess.GetDtCrossingRoadByTableId(dr[0].ToString());

                hstTimeTableWithCrossingRoad.Add(dr[1].ToString(), dtCrossingRoad);
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("获取时刻表：" + dr[1].ToString());

            }

        }

        public void SetTimeTableWithCrossingRoad(string startDay, string endDay)
        {
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("获取时刻表对应交路");
            hstTimeTableWithCrossingRoad.Clear();
            // Hashtable hstTimeTableWithCrossingRoad = new Hashtable();
            DataTable dtTimeTableID = _teamAccess.GetDtMonthTimeTableId(startDay, endDay);

            foreach (DataRow dr in dtTimeTableID.Rows)
            {

                DataTable dtCrossingRoad = _teamAccess.GetDtCrossingRoadByTableId(dr[0].ToString());

                hstTimeTableWithCrossingRoad.Add(dr[1].ToString(), dtCrossingRoad);
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("获取时刻表：" + dr[1].ToString());

            }

        }
        #endregion
        #region 交路分配给司机
        //public bool SetCrossingRoadToDriver(int year, int month)
        //{
        //    try
        //    {
        //        //查找轮班情况
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("开始交路分配给司机");
        //        DataTable dtLastClassTrue = _teamAccess.GetLastClass();
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("读取轮班计划表最后一天数据");
        //        if (dtLastClassTrue.Rows.Count != 4)
        //        {
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("计划班表无数据 读取当前排班信息");
        //            //没有计划排过，那么读取当前的
        //            dtLastClassTrue = _teamAccess.GetCurrentClass();
        //        }

        //        //初始化当前班次
        //        CurrentRunningTrem currentRunningTrem = InitRunningTrem(dtLastClassTrue);

        //        if (currentRunningTrem == null)
        //        {
        //            MessageBoxHelper.ShowError("初始化班次失败");
        //            return false;
        //        }
        //        //获取一张轮班计划的空表
        //        DataTable dtClassTrunPlane = _teamAccess.GetDtClassTrunPlane();

        //        //获取一张司机组_交路的空表
        //        DataTable dtDriverCombineCrossingRoadPlane = _teamAccess.GetDtDriverCombineCrossingRoadPlane();

        //        //获取最后一天的夜班司机退勤信息

        //        DataTable dtYBoffInfo = _teamAccess.GetDtLastybInfo();

        //        //获取基础司机所有司机组的信息
        //        DataTable dtDriverCombine = _teamAccess.GetDtDriverCombine();

        //        //获取一张空的司机组表用来填充数据
        //        DataTable dtEmptyDriverCombine = _teamAccess.GetEmptyDriverCombine();

        //        //获取整个月时刻表信息
        //        DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimeTableId(year, month);

        //        //记录上个月月备班人员
        //        Hashtable hstMonthsBBDriver = GetHstMonthsBB(dtDriverCombine);

        //        //记录每组车站工作人员的位置
        //        TeamStationIndex teamOne = SetTeamStationIndex(dtDriverCombine, "1");
        //        TeamStationIndex teamTwo = SetTeamStationIndex(dtDriverCombine, "2");
        //        TeamStationIndex teamThree = SetTeamStationIndex(dtDriverCombine, "3");
        //        TeamStationIndex teamFour = SetTeamStationIndex(dtDriverCombine, "4");

        //        //遍历一个月的时刻班表
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("==================初始化数据完成 开始按每天交路交司机====================");
        //        int daysTime = 0;
        //        foreach (var de in hstTimeTableNameWithDate)
        //        {
        //            //获取今天时刻表的信息
        //            daysTime++;
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("进行" + de.Key + "交路交司机==");
        //            DataRow[] drTableTimeInfo = dtMonthTimeTable.Select("TableName='" + de.Value + "'");

        //            //拿出今天所对应的交路
        //            DataTable dtCrossingRoad = (DataTable)hstTimeTableWithCrossingRoad[de.Value];

        //            //System.Int32
        //            if (dtCrossingRoad.Columns.Contains("realityTime") || dtCrossingRoad.Columns.Contains("offSeq"))
        //            { }
        //            else
        //            {
        //                dtCrossingRoad.Columns.Add("realityTime", Type.GetType("System.String"));
        //                dtCrossingRoad.Columns.Add("offSeq", Type.GetType("System.Int32"));
        //            }
        //            //设置交路的退勤时间
        //            setCrossingRoadOffTime(ref dtCrossingRoad, de);
        //            //进行轮班(插入记录到轮班表)
        //            TrunClass(ref dtClassTrunPlane, ref currentRunningTrem, de.Key.ToString());
        //            //根据早休夜白来分配交路
        //            //获取早班正线交路和车场交路
        //            DataRow[] drzbCrossingRoad = dtCrossingRoad.Select("grp_id=5 and zby=0");
        //            DataRow[] drzbStationCrossingRoad = dtCrossingRoad.Select("grp_id<>5 and zby=0");

        //            string strzbCrossingRoadType = "";
        //            foreach (DataRow drzbCrossingRoadType in drzbStationCrossingRoad)
        //            {
        //                strzbCrossingRoadType = strzbCrossingRoadType + drzbCrossingRoadType["grp_id"].ToString() + ",";
        //            }
        //            strzbCrossingRoadType = strzbCrossingRoadType + "0";
        //            //获取白班正线交路和车场交路
        //            DataRow[] drbbCrossingRoad = dtCrossingRoad.Select("grp_id=5 and zby=2");
        //            DataRow[] drbbStationCrossingRoad = dtCrossingRoad.Select("grp_id<>5 and zby=2");
        //            //获取夜班正线交路和车场交路
        //            DataRow[] drybCrossingRoad = dtCrossingRoad.Select("grp_id=5 and zby=3");
        //            DataRow[] drybStationCrossingRoad = dtCrossingRoad.Select("grp_id<>5 and zby=3");


        //            //早班司机
        //            DataRow[] drzbDriver;
        //            DataRow[] drzbStationDriver;
        //            if (dtYBoffInfo.Rows.Count == 0)
        //            {
        //                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("在司机表读取早班司机");
        //                drzbDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.zb + "' and dcom_grp_type not in (" + strzbCrossingRoadType + ") ", "dcom_ybarrive asc");
        //                drzbStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.zb + "' and dcom_grp_type in(" + strzbCrossingRoadType + ")");
        //            }
        //            else
        //            {

        //                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("从夜班司机读取早班司机");
        //                drzbDriver = dtYBoffInfo.Select("dcdr_driverType not in (" + strzbCrossingRoadType + ")", "dcdr_crossoffTime asc");
        //                drzbStationDriver = dtYBoffInfo.Select("dcdr_driverType in (" + strzbCrossingRoadType + ")");
        //            }

        //            //获取真正的早班正线司机和车场司机


        //            //白班司机数据
        //            DataRow[] drbbDriver;
        //            DataRow[] drbbStationDriver;
        //            drbbDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.bb + "' and dcom_grp_type=5", "dcom_dutynum asc");
        //            drbbStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.bb + "' and dcom_grp_type<>5");

        //            //晚班司机数据
        //            DataRow[] drybDriver;
        //            DataRow[] drybStationDriver;
        //            drybDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.yb + "' and dcom_grp_type=5", "dcom_dutynum asc");
        //            drybStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.yb + "' and dcom_grp_type<>5");

        //            //获取休班司机数据
        //            //休班司机
        //            DataRow[] drxbDriver;
        //            drxbDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "'", "dcom_dutynum asc");

        //            //早班正线司机
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配早班正线司机");
        //            for (int i = 0; i < drzbDriver.Length; i++)
        //            {
        //                if (i < drzbCrossingRoad.Length)
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbDriver[i], drTableTimeInfo[0], drzbCrossingRoad[i], de, "0", ref dtEmptyDriverCombine);

        //                }
        //                else
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbDriver[i], drTableTimeInfo[0], null, de, "0", ref dtEmptyDriverCombine);

        //                }

        //            }
        //            //早班车场司机
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配早班车场司机");
        //            TeamStationIndex teamStationIndex = FindTeamStationIndex(currentRunningTrem.zb.ToString(), teamOne, teamTwo, teamThree, teamFour);
        //            for (int i = 0; i < drzbStationDriver.Length; i++)
        //            {
        //                if (i < drzbStationCrossingRoad.Length)
        //                {
        //                    int index = FindCrossingRoadIndex(drzbStationCrossingRoad, drzbStationDriver[i][1].ToString());
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbStationDriver[i], drTableTimeInfo[0], drzbStationCrossingRoad[index], de, "0", ref dtEmptyDriverCombine);

        //                }
        //                else
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbStationDriver[i], drTableTimeInfo[0], null, de, "0", ref dtEmptyDriverCombine);


        //                }
        //            }



        //            //drxbStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "' and dcom_grp_type<>5");
        //            //每个司机+1
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配休班车场司机");
        //            TeamStationIndex teamStationIndexxb = FindTeamStationIndex(currentRunningTrem.xb.ToString(), teamOne, teamTwo, teamThree, teamFour);
        //            for (int i = 0; i < drxbDriver.Length; i++)
        //            {
        //                AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.xb, drxbDriver[i], drTableTimeInfo[0], null, de, "1", ref dtEmptyDriverCombine);

        //                //班组轮转

        //                //夜备班不进行轮转
        //                if (!teamStationIndexxb.ybb.Contains(Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString())))
        //                {

        //                    if (i == drxbDriver.Length - 1)
        //                    {
        //                        drxbDriver[i]["dcom_dutynum"] = "1";

        //                    }
        //                    else
        //                    {
        //                        drxbDriver[i]["dcom_dutynum"] = Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) + 1;
        //                    }
        //                    //判断是否刚好等于月备班，如果刚好等于月备班+1
        //                    if (Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) == teamStationIndexxb.ybb)
        //                    {
        //                        drxbDriver[i]["dcom_dutynum"] = Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) + 1;
        //                    }
        //                }



        //                //重新设置车场轮询号
        //                if (teamStationIndexxb.bb.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
        //                {
        //                    drxbDriver[i]["dcom_grp_type"] = "4";
        //                    //判断这个队有没有月备班

        //                }
        //                else if (teamStationIndexxb.rb.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
        //                {
        //                    drxbDriver[i]["dcom_grp_type"] = "1";
        //                }
        //                else if (teamStationIndexxb.scx.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
        //                {
        //                    drxbDriver[i]["dcom_grp_type"] = "3";
        //                }
        //                else if (teamStationIndexxb.dcx.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
        //                {
        //                    drxbDriver[i]["dcom_grp_type"] = "2";
        //                }
        //                else if (teamStationIndexxb.ybb.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
        //                {
        //                    //drxbDriver[i]["dcom_grp_type"] = "6";
        //                    if (hstMonthsBBDriver.Contains(drxbDriver[i]["dcom_team"].ToString()))
        //                    {
        //                        //有月备班人员
        //                        //判断上个月备班人员和当前月备班人员是否一样
        //                        if (hstMonthsBBDriver[drxbDriver[i]["dcom_team"].ToString()].ToString() == drxbDriver[i]["ID"].ToString())
        //                        {
        //                            int tempNum = 0;
        //                            if (Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) == drxbDriver.Length - 1)
        //                            {
        //                                tempNum = 1;
        //                            }
        //                            else
        //                            {
        //                                tempNum = Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) + 1;
        //                            }


        //                            //查找出这个月备班人员的信息
        //                            DataRow[] drXBByBB = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "' and dcom_dutynum=" + tempNum + "");
        //                            if (drXBByBB.Length > 0)
        //                            {
        //                                string tempType = drXBByBB[0]["dcom_grp_type"].ToString();
        //                                drXBByBB[0]["dcom_dutynum"] = drxbDriver[i]["dcom_dutynum"].ToString();
        //                                drXBByBB[0]["dcom_grp_type"] = "6";
        //                                drxbDriver[i]["dcom_dutynum"] = tempNum;
        //                                drxbDriver[i]["dcom_grp_type"] = tempType;
        //                            }
        //                        }
        //                        //一样的话进行和备班进行替换
        //                        //不一样不做修改
        //                    }
        //                }
        //                else
        //                {
        //                    drxbDriver[i]["dcom_grp_type"] = "5";
        //                }


        //            }



        //            //白班司机

        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配白班正线司机");
        //            for (int i = 0; i < drbbDriver.Length; i++)
        //            {
        //                if (i < drbbCrossingRoad.Length)
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbDriver[i], drTableTimeInfo[0], drbbCrossingRoad[i], de, "2", ref dtEmptyDriverCombine);

        //                }
        //                else
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbDriver[i], drTableTimeInfo[0], null, de, "2", ref dtEmptyDriverCombine);

        //                }

        //            }

        //            //设置车场人员
        //            //TeamStationIndex teamStationIndexbb = FindTeamStationIndex(currentRunningTrem.bb.ToString(), teamOne, teamTwo, teamThree, teamFour);
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配白班车场司机");
        //            for (int i = 0; i < drbbStationDriver.Length; i++)
        //            {
        //                if (i < drbbStationCrossingRoad.Length)
        //                {
        //                    int index = FindCrossingRoadIndex(drbbStationCrossingRoad, drbbStationDriver[i]["dcom_grp_type"].ToString());
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbStationDriver[i], drTableTimeInfo[0], drbbStationCrossingRoad[index], de, "2", ref dtEmptyDriverCombine);

        //                }
        //                else
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbStationDriver[i], drTableTimeInfo[0], null, de, "2", ref dtEmptyDriverCombine);

        //                }

        //            }

        //            //夜班司机


        //            dtYBoffInfo.Rows.Clear();
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配夜班正线司机");
        //            for (int i = 0; i < drybDriver.Length; i++)
        //            {
        //                if (i < drybCrossingRoad.Length)
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybDriver[i], drTableTimeInfo[0], drybCrossingRoad[i], de, "3", ref dtEmptyDriverCombine);

        //                    #region 加入夜班表

        //                    DataRow dr = dtYBoffInfo.NewRow();
        //                    dr[0] = drybDriver[i]["ID"].ToString();
        //                    dr[1] = drybDriver[i]["dcom_grp_type"].ToString();
        //                    dr[2] = currentRunningTrem.zb;
        //                    dr[3] = drybDriver[i]["dcom_dutynum"].ToString();
        //                    if (!string.IsNullOrEmpty(drybDriver[i]["dcom_opdriver"].ToString()))
        //                    {
        //                        dr[5] = drybDriver[i]["dcom_opdriver"].ToString();
        //                    }
        //                    if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriver"].ToString()))
        //                    {
        //                        dr[6] = drybDriver[i]["dcom_monidriver"].ToString();
        //                    }
        //                    if (Convert.ToDateTime(drybCrossingRoad[i]["offTime"].ToString()) < Convert.ToDateTime(drybCrossingRoad[i]["attenTime"].ToString()))
        //                    {
        //                        //dr[4] ="1"+ drybCrossingRoad[i]["offTime"].ToString();
        //                        dr[4] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybCrossingRoad[i]["offTime"].ToString();
        //                    }
        //                    else
        //                    {
        //                        dr[4] = de.Key.ToString() + " " + drybCrossingRoad[i]["offTime"].ToString();
        //                    }


        //                    dtYBoffInfo.Rows.Add(dr);
        //                    #endregion
        //                }
        //                else
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybDriver[i], drTableTimeInfo[0], null, de, "3", ref dtEmptyDriverCombine);

        //                    #region

        //                    DataRow dr = dtYBoffInfo.NewRow();
        //                    dr[0] = drybDriver[i]["ID"].ToString();
        //                    dr[1] = drybDriver[i]["dcom_grp_type"].ToString();
        //                    dr[2] = currentRunningTrem.zb;
        //                    dr[3] = drybDriver[i]["dcom_dutynum"].ToString();
        //                    dr[4] = DBNull.Value;
        //                    if (!string.IsNullOrEmpty(drybDriver[i]["dcom_opdriver"].ToString()))
        //                    {
        //                        dr[5] = drybDriver[i]["dcom_opdriver"].ToString();
        //                    }
        //                    if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriver"].ToString()))
        //                    {
        //                        dr[6] = drybDriver[i]["dcom_monidriver"].ToString();
        //                    }
        //                    if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriverTwo"].ToString()))
        //                    {
        //                        dr[7] = drybStationDriver[i]["dcom_monidriverTwo"].ToString();
        //                    }
        //                    dtYBoffInfo.Rows.Add(dr);
        //                    #endregion
        //                }

        //            }

        //            //设置夜班车场人员
        //            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配夜班车场司机");
        //            TeamStationIndex teamStationIndexyb = FindTeamStationIndex(currentRunningTrem.yb.ToString(), teamOne, teamTwo, teamThree, teamFour);
        //            for (int i = 0; i < drybStationDriver.Length; i++)
        //            {
        //                if (i < drybStationCrossingRoad.Length)
        //                {
        //                    int index = FindCrossingRoadIndex(drybStationCrossingRoad, drybStationDriver[i]["dcom_grp_type"].ToString());
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybStationDriver[i], drTableTimeInfo[0], drybStationCrossingRoad[index], de, "3", ref dtEmptyDriverCombine);

        //                    #region
        //                    //增加进夜班表

        //                    DataRow dr = dtYBoffInfo.NewRow();
        //                    dr[0] = drybStationDriver[i]["ID"].ToString();
        //                    dr[1] = drybStationDriver[i]["dcom_grp_type"].ToString();
        //                    dr[2] = currentRunningTrem.zb;
        //                    dr[3] = drybStationDriver[i]["dcom_dutynum"].ToString();
        //                    if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_opdriver"].ToString()))
        //                    {
        //                        dr[5] = drybStationDriver[i]["dcom_opdriver"].ToString();
        //                    }
        //                    if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriver"].ToString()))
        //                    {
        //                        dr[6] = drybStationDriver[i]["dcom_monidriver"].ToString();
        //                    }
        //                    if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriverTwo"].ToString()))
        //                    {
        //                        dr[7] = drybStationDriver[i]["dcom_monidriverTwo"].ToString();
        //                    }
        //                    if (Convert.ToDateTime(drybStationCrossingRoad[i]["offTime"].ToString()) < Convert.ToDateTime(drybStationCrossingRoad[i]["attenTime"].ToString()))
        //                    {
        //                        dr[4] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybStationCrossingRoad[i]["offTime"].ToString();
        //                    }
        //                    else
        //                    {
        //                        dr[4] = de.Key.ToString() + " " + drybStationCrossingRoad[index]["offTime"].ToString();
        //                    }
        //                    dtYBoffInfo.Rows.Add(dr);
        //                    #endregion
        //                }
        //                else
        //                {
        //                    AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybStationDriver[i], drTableTimeInfo[0], null, de, "3", ref dtEmptyDriverCombine);

        //                    #region

        //                    DataRow dr = dtYBoffInfo.NewRow();
        //                    dr[0] = drybStationDriver[i]["ID"].ToString();
        //                    dr[1] = drybStationDriver[i]["dcom_grp_type"].ToString();
        //                    dr[2] = currentRunningTrem.zb;
        //                    dr[3] = drybStationDriver[i]["dcom_dutynum"].ToString();
        //                    dr[4] = DBNull.Value;
        //                    if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_opdriver"].ToString()))
        //                    {
        //                        dr[5] = drybStationDriver[i]["dcom_opdriver"].ToString();
        //                    }
        //                    if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriver"].ToString()))
        //                    {
        //                        dr[6] = drybStationDriver[i]["dcom_monidriver"].ToString();
        //                    }
        //                    dtYBoffInfo.Rows.Add(dr);
        //                    #endregion
        //                }
        //            }
        //            //夜班按退勤时间排序


        //        }
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("====================交路分配司机结束==========================");
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("====================开始将数据写入数据库==========================");
        //        //写入数据库
        //        //轮班
        //        _teamAccess.SetClassTurnPlane(dtClassTrunPlane);
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入ClassTurnPlane");
        //        //插入计划司机
        //        _teamAccess.SetDriverCombine(dtEmptyDriverCombine);
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入DriverCombine");
        //        //周月计划
        //        _teamAccess.SetDriverCombineCrossingRoadPlane(dtDriverCombineCrossingRoadPlane);
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入dtDriverCombineCrossingRoadPlane");
        //        //写入计划
        //        _teamAccess.AddClassTurnPlaneRecord(year, month);
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入ClassTurnPlaneRecord");
        //        //把基础数据更改为最后一天的的数据

        //        _teamAccess.UpdateDriver(year.ToString() + "-" + month.ToString() + "-" + DateTime.DaysInMonth(year, month).ToString());
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("更新基础司机表的序号");
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("====================将数据写入数据库结束==========================");
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError("轮班逻辑失败" + ex.ToString());
        //        // MessageBoxHelper.ShowError("轮班失败" + ex.Message);
        //        return false;
        //    }

        //}

        #endregion
        int y = 0;
        public bool SetCrossingRoadToDriver(string startDay, string endDay)
        {

            string tranId = null;
            try
            {
                bool isNewClassPlaneRec = true;

                isNewClassPlaneRec = isNewclassPlane(startDay);
                //查找轮班情况
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("开始交路分配给司机");
                DataTable dtLastClassTrue = _teamAccess.GetLastClass(startDay);
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("读取轮班计划表最后一天数据");
                if (dtLastClassTrue.Rows.Count != 4)
                {
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("计划班表无数据 读取当前排班信息");
                    //没有计划排过，那么读取当前的
                    dtLastClassTrue = _teamAccess.GetCurrentClass();
                }

                //初始化当前班次
                CurrentRunningTrem currentRunningTrem = InitRunningTrem(dtLastClassTrue);

                if (currentRunningTrem == null)
                {
                    MessageBoxHelper.ShowError("初始化班次失败");
                    return false;
                }
                //获取一张轮班计划的空表
                DataTable dtClassTrunPlane = _teamAccess.GetDtClassTrunPlane();

                //获取一张司机组_交路的空表
                DataTable dtDriverCombineCrossingRoadPlane = _teamAccess.GetDtDriverCombineCrossingRoadPlane();

                //获取最后一天的夜班司机退勤信息

                DataTable dtYBoffInfo = _teamAccess.GetDtLastybInfo();

                //获取基础司机所有司机组的信息
                DataTable dtDriverCombine = _teamAccess.GetDtDriverCombine();

                dtDriverCombine = SetDriverCombinWithYBSeq(dtDriverCombine, startDay);

                //获取一张空的司机组表用来填充数据
                DataTable dtEmptyDriverCombine = _teamAccess.GetEmptyDriverCombine();

                //获取整个月时刻表信息
                DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimeTableId(startDay, endDay);

                //记录上个月月备班人员
                // Hashtable hstMonthsBBDriver = GetHstMonthsBB(dtDriverCombine);

                //记录每组车站工作人员的位置
                TeamStationIndex teamOne = SetTeamStationIndex(dtDriverCombine, "1");
                TeamStationIndex teamTwo = SetTeamStationIndex(dtDriverCombine, "2");
                TeamStationIndex teamThree = SetTeamStationIndex(dtDriverCombine, "3");
                TeamStationIndex teamFour = SetTeamStationIndex(dtDriverCombine, "4");

                //遍历一个月的时刻班表
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("==================初始化数据完成 开始按每天交路交司机====================");
                int daysTime = 0;
                foreach (var de in hstTimeTableNameWithDate)
                {
                    //获取今天时刻表的信息
                    daysTime++;
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("进行" + de.Key + "交路交司机==");
                    DataRow[] drTableTimeInfo = dtMonthTimeTable.Select("TableName='" + de.Value + "'");

                    //拿出今天所对应的交路
                    DataTable dtCrossingRoad = (DataTable)hstTimeTableWithCrossingRoad[de.Value];

                    //System.Int32
                    if (dtCrossingRoad.Columns.Contains("realityTime") || dtCrossingRoad.Columns.Contains("offSeq"))
                    { }
                    else
                    {
                        dtCrossingRoad.Columns.Add("realityTime", Type.GetType("System.String"));
                        dtCrossingRoad.Columns.Add("offSeq", Type.GetType("System.Int32"));
                    }
                    //设置交路的退勤时间
                    setCrossingRoadOffTime(ref dtCrossingRoad, de);
                    //进行轮班(插入记录到轮班表)
                    TrunClass(ref dtClassTrunPlane, ref currentRunningTrem, de.Key.ToString());
                    //根据早休夜白来分配交路
                    //获取早班正线交路和车场交路
                    //DataRow[] drzbCrossingRoad = dtCrossingRoad.Select("grp_id=5 and zby=0", "number asc");
                    //DataRow[] drzbStationCrossingRoad = dtCrossingRoad.Select("grp_id<>5 and zby=0");
                    DataRow[] drzbCrossingRoad = dtCrossingRoad.Select("(grp_id=5 or grp_id=1) and zby=0", "number asc");
                    DataRow[] drzbStationCrossingRoad = dtCrossingRoad.Select("(grp_id<>5 and grp_id<>1) and zby=0");

                    //早班非正线司机只有月备班和司机长
                    string strzbCrossingRoadType = " ";
                    foreach (DataRow drzbCrossingRoadType in drzbStationCrossingRoad)
                    {
                        strzbCrossingRoadType = strzbCrossingRoadType + drzbCrossingRoadType["grp_id"].ToString() + ",";
                    }
                    strzbCrossingRoadType = strzbCrossingRoadType + "0";
                    //获取白班正线交路和车场交路
                    DataRow[] drbbCrossingRoad = dtCrossingRoad.Select("grp_id=5  and zby=2");
                    DataRow[] drbbStationCrossingRoad = dtCrossingRoad.Select("grp_id<>5 and zby=2");
                    //获取夜班正线交路和车场交路
                    DataRow[] drybCrossingRoad = dtCrossingRoad.Select("grp_id=5 and zby=3");
                    DataRow[] drybStationCrossingRoad = dtCrossingRoad.Select("grp_id<>5 and zby=3");


                    //早班司机
                    DataRow[] drzbDriver;
                    DataRow[] drzbStationDriver;
                    if (dtYBoffInfo.Rows.Count == 0)
                    {
                        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("在司机表读取早班司机");
                        drzbDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.zb + "' and dcom_grp_type not in (" + strzbCrossingRoadType + ") ", "crsOffTime asc,crsLastTrainTime asc");
                        drzbStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.zb + "' and dcom_grp_type in(" + strzbCrossingRoadType + ")");
                    }
                    else
                    {

                        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("从夜班司机读取早班司机");
                        drzbDriver = dtYBoffInfo.Select("dcdr_driverType not in (" + strzbCrossingRoadType + ")", "dcdr_crossoffTime asc,lastTrainTime asc");
                        drzbStationDriver = dtYBoffInfo.Select("dcdr_driverType in (" + strzbCrossingRoadType + ")");
                    }

                    //获取真正的早班正线司机和车场司机


                    //白班司机数据
                    DataRow[] drbbDriver;
                    DataRow[] drbbStationDriver;
                    drbbDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.bb + "' and dcom_grp_type=5", "dcom_dutynum asc");
                    drbbStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.bb + "' and dcom_grp_type<>5");

                    //晚班司机数据
                    DataRow[] drybDriver;
                    DataRow[] drybStationDriver;
                    drybDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.yb + "' and dcom_grp_type=5", "dcom_dutynum asc");
                    drybStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.yb + "' and dcom_grp_type<>5");

                    //获取休班司机数据
                    //休班司机
                    DataRow[] drxbDriver;
                    drxbDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "'", "dcom_dutynum asc");

                    //早班正线司机
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配早班正线司机");
                    for (int i = 0; i < drzbDriver.Length; i++)
                    {
                        if (i < drzbCrossingRoad.Length)
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbDriver[i], drTableTimeInfo[0], drzbCrossingRoad[i], de, "0", ref dtEmptyDriverCombine);

                        }
                        else
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbDriver[i], drTableTimeInfo[0], null, de, "0", ref dtEmptyDriverCombine);

                        }

                    }
                    //早班车场司机
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配早班车场司机");
                    TeamStationIndex teamStationIndex = FindTeamStationIndex(currentRunningTrem.zb.ToString(), teamOne, teamTwo, teamThree, teamFour);
                    for (int i = 0; i < drzbStationDriver.Length; i++)
                    {
                        int index = FindCrossingRoadIndex(drzbStationCrossingRoad, drzbStationDriver[i][1].ToString());
                        if (index != -1)
                        {

                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbStationDriver[i], drTableTimeInfo[0], drzbStationCrossingRoad[index], de, "0", ref dtEmptyDriverCombine);

                        }
                        else
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.zb, drzbStationDriver[i], drTableTimeInfo[0], null, de, "0", ref dtEmptyDriverCombine);


                        }
                    }



                    //drxbStationDriver = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "' and dcom_grp_type<>5");
                    //每个司机+1
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配休班车场司机");
                    TeamStationIndex teamStationIndexxb = FindTeamStationIndex(currentRunningTrem.xb.ToString(), teamOne, teamTwo, teamThree, teamFour);
                    for (int i = 0; i < drxbDriver.Length; i++)
                    {


                        //班组轮转

                        //月备班不进行轮转   
                        if (!teamStationIndexxb.ybb.Contains(Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString())) && Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) != teamStationIndexxb.sjz && Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) != teamStationIndexxb.ddy)
                        {

                            if (i == drxbDriver.Length - 1)
                            {
                                drxbDriver[i]["dcom_dutynum"] = "1";

                            }
                            else
                            {
                                drxbDriver[i]["dcom_dutynum"] = Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) + 1;
                            }
                            //判断是否刚好等于月备班，如果刚好等于月备班+1
                            while (teamStationIndexxb.ybb.Contains(Convert.ToInt32(Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()))) || Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) == teamStationIndexxb.sjz || Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) == teamStationIndexxb.ddy)
                            {
                                drxbDriver[i]["dcom_dutynum"] = Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) + 1;
                                if (Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) > drxbDriver.Length)
                                {
                                    drxbDriver[i]["dcom_dutynum"] = "1";
                                }

                            }

                        }


                        //重新设置车场轮询号
                        if (teamStationIndexxb.bb.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
                        {
                            drxbDriver[i]["dcom_grp_type"] = "4";
                            //判断这个队有没有月备班

                        }
                        else if (teamStationIndexxb.rb.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
                        {
                            drxbDriver[i]["dcom_grp_type"] = "1";
                        }
                        else if (teamStationIndexxb.scx.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
                        {
                            drxbDriver[i]["dcom_grp_type"] = "3";
                        }
                        else if (teamStationIndexxb.dcx.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
                        {
                            drxbDriver[i]["dcom_grp_type"] = "2";
                        }
                        else if (teamStationIndexxb.ybb.Contains(Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString())))
                        {
                            drxbDriver[i]["dcom_grp_type"] = "6";

                            //查找上个月最后一天的月备班
                            //string lastMonthYbbDriver = GetLastMonthYBBDriver(dtDriverCombineCrossingRoadPlane, de.Key.ToString(), drxbDriver[i]["dcom_team"].ToString());
                            // if(!string.IsNullOrEmpty(lastMonthYbbDriver))
                            //{
                            //    //有月备班人员
                            //    //判断上个月备班人员和当前月备班人员是否一样
                            //    if (lastMonthYbbDriver == drxbDriver[i]["ID"].ToString())
                            //    {
                            //        int tempNum = 0;
                            //        if (Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) == drxbDriver.Length )
                            //        {
                            //            tempNum = 1;
                            //        }
                            //        else
                            //        {
                            //            tempNum = Convert.ToInt32(drxbDriver[i]["dcom_dutynum"].ToString()) + 1;
                            //        }


                            //        //查找出这个月备班人员的信息
                            //        DataRow[] drXBByBB = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "' and dcom_dutynum=" + tempNum + "");
                            //        if (drXBByBB.Length > 0)
                            //        {
                            //            string tempType = drXBByBB[0]["dcom_grp_type"].ToString();
                            //            drXBByBB[0]["dcom_dutynum"] = drxbDriver[i]["dcom_dutynum"].ToString();
                            //            drXBByBB[0]["dcom_grp_type"] = "6";
                            //            drxbDriver[i]["dcom_dutynum"] = tempNum;
                            //            drxbDriver[i]["dcom_grp_type"] = tempType;
                            //        }
                            //    }
                            //    //一样的话进行和备班进行替换
                            //    //不一样不做修改
                            //}
                        }
                        else if (teamStationIndexxb.sjz.ToString() == drxbDriver[i]["dcom_dutynum"].ToString())
                        {
                            drxbDriver[i]["dcom_grp_type"] = "7";
                        }
                        else if (teamStationIndexxb.ddy.ToString()==drxbDriver[i]["dcom_dutynum"].ToString())
                        {
                            drxbDriver[i]["dcom_grp_type"] = "8";
                        }
                        else
                        {
                            drxbDriver[i]["dcom_grp_type"] = "5";
                        }

                        AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.xb, drxbDriver[i], drTableTimeInfo[0], null, de, "1", ref dtEmptyDriverCombine);
                    }

                    //替换月备司机
                    #region 现在改为月备司机不进行轮班

                    //string lastMonthYbbDriver = GetLastMonthYBBDriver(dtDriverCombineCrossingRoadPlane, de.Key.ToString(), currentRunningTrem.xb.ToString());

                    //if (!string.IsNullOrEmpty(lastMonthYbbDriver))
                    //{
                    //    //有月备班人员
                    //    //判断上个月备班人员和当前月备班人员是否一样
                    //    //获取当前的月备班司机
                    //    DataRow[] drCurrentXBByBB = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "' and dcom_grp_type=6");
                    //    if(drCurrentXBByBB.Length>0)
                    //    {
                    //    if (lastMonthYbbDriver == drCurrentXBByBB[0]["ID"].ToString())
                    //    {
                    //        int tempNum = 0;
                    //        if (Convert.ToInt32(drCurrentXBByBB[0]["dcom_dutynum"].ToString()) == drxbDriver.Length)
                    //        {
                    //            tempNum = 1;
                    //        }
                    //        else
                    //        {
                    //            tempNum = Convert.ToInt32(drCurrentXBByBB[0]["dcom_dutynum"].ToString()) + 1;
                    //        }


                    //        //查找出这个月备班人员的信息
                    //        DataRow[] drXBByBB = dtDriverCombine.Select("dcom_team='" + currentRunningTrem.xb + "' and dcom_dutynum=" + tempNum + "");
                    //        if (drXBByBB.Length > 0)
                    //        {
                    //            string tempType = drXBByBB[0]["dcom_grp_type"].ToString();
                    //            drXBByBB[0]["dcom_dutynum"] = drCurrentXBByBB[0]["dcom_dutynum"].ToString();
                    //            drXBByBB[0]["dcom_grp_type"] = "6";
                    //            drCurrentXBByBB[0]["dcom_dutynum"] = tempNum;
                    //            drCurrentXBByBB[0]["dcom_grp_type"] = tempType;
                    //        }
                    //    }
                    //    //一样的话进行和备班进行替换
                    //    //不一样不做修改
                    //   }
                    //}
                    #endregion

                    //白班司机

                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配白班正线司机");
                    for (int i = 0; i < drbbDriver.Length; i++)
                    {
                        if (i < drbbCrossingRoad.Length)
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbDriver[i], drTableTimeInfo[0], drbbCrossingRoad[i], de, "2", ref dtEmptyDriverCombine);

                        }
                        else
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbDriver[i], drTableTimeInfo[0], null, de, "2", ref dtEmptyDriverCombine);

                        }

                    }

                    //设置车场人员
                    //TeamStationIndex teamStationIndexbb = FindTeamStationIndex(currentRunningTrem.bb.ToString(), teamOne, teamTwo, teamThree, teamFour);
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配白班车场司机");
                    for (int i = 0; i < drbbStationDriver.Length; i++)
                    {
                        int index = FindCrossingRoadIndex(drbbStationCrossingRoad, drbbStationDriver[i]["dcom_grp_type"].ToString());
                        if (index != -1)
                        {

                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbStationDriver[i], drTableTimeInfo[0], drbbStationCrossingRoad[index], de, "2", ref dtEmptyDriverCombine);

                        }
                        else
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.bb, drbbStationDriver[i], drTableTimeInfo[0], null, de, "2", ref dtEmptyDriverCombine);



                        }
        #endregion
                    }

                    //夜班司机


                    dtYBoffInfo.Rows.Clear();
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配夜班正线司机");
                    for (int i = 0; i < drybDriver.Length; i++)
                    {
                        if (i < drybCrossingRoad.Length)
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybDriver[i], drTableTimeInfo[0], drybCrossingRoad[i], de, "3", ref dtEmptyDriverCombine);

                            #region 加入夜班表

                            DataRow dr = dtYBoffInfo.NewRow();
                            dr[0] = drybDriver[i]["ID"].ToString();
                            dr[1] = drybDriver[i]["dcom_grp_type"].ToString();
                            dr[2] = currentRunningTrem.zb;
                            dr[3] = drybDriver[i]["dcom_dutynum"].ToString();
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_opdriver"].ToString()))
                            {
                                dr[5] = drybDriver[i]["dcom_opdriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriver"].ToString()))
                            {
                                dr[6] = drybDriver[i]["dcom_monidriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriverTwo"].ToString()))
                            {
                                dr[7] = drybDriver[i]["dcom_monidriverTwo"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriverThree"].ToString()))
                            {
                                dr[10] = drybDriver[i]["dcom_monidriverThree"].ToString();
                            }
                            if (Convert.ToDateTime(drybCrossingRoad[i]["offTime"].ToString()) < Convert.ToDateTime(drybCrossingRoad[i]["attenTime"].ToString()))
                            {
                                //dr[4] ="1"+ drybCrossingRoad[i]["offTime"].ToString();
                                dr[4] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybCrossingRoad[i]["offTime"].ToString();
                            }
                            else
                            {
                                dr[4] = de.Key.ToString() + " " + drybCrossingRoad[i]["offTime"].ToString();
                            }
                            if (string.IsNullOrEmpty(drybCrossingRoad[i]["lastTrainTime"].ToString()))
                            {
                                drybCrossingRoad[i]["lastTrainTime"] = drybCrossingRoad[i]["offTime"].ToString();
                            }

                            if (Convert.ToDateTime(drybCrossingRoad[i]["lastTrainTime"].ToString()) < Convert.ToDateTime(drybCrossingRoad[i]["attenTime"].ToString()))
                            {
                                //dr[4] ="1"+ drybCrossingRoad[i]["offTime"].ToString();
                                dr[8] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybCrossingRoad[i]["lastTrainTime"].ToString();
                            }
                            else
                            {
                                dr[8] = de.Key.ToString() + " " + drybCrossingRoad[i]["lastTrainTime"].ToString();
                            }


                            dr[9] = drybDriver[i]["dcom_NO"].ToString();



                            dtYBoffInfo.Rows.Add(dr);
                            #endregion
                        }
                        else
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybDriver[i], drTableTimeInfo[0], null, de, "3", ref dtEmptyDriverCombine);

                            #region

                            DataRow dr = dtYBoffInfo.NewRow();
                            dr[0] = drybDriver[i]["ID"].ToString();
                            dr[1] = drybDriver[i]["dcom_grp_type"].ToString();
                            dr[2] = currentRunningTrem.zb;
                            dr[3] = drybDriver[i]["dcom_dutynum"].ToString();
                            dr[4] = DBNull.Value;
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_opdriver"].ToString()))
                            {
                                dr[5] = drybDriver[i]["dcom_opdriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriver"].ToString()))
                            {
                                dr[6] = drybDriver[i]["dcom_monidriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriverTwo"].ToString()))
                            {
                                dr[7] = drybDriver[i]["dcom_monidriverTwo"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybDriver[i]["dcom_monidriverThree"].ToString()))
                            {
                                dr[10] = drybDriver[i]["dcom_monidriverThree"].ToString();
                            }
                            dr[8] = DBNull.Value;
                            dr[9] = drybDriver[i]["dcom_NO"].ToString();
                            dtYBoffInfo.Rows.Add(dr);
                            #endregion
                        }

                    }

                    //设置夜班车场人员
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("分配夜班车场司机");
                    TeamStationIndex teamStationIndexyb = FindTeamStationIndex(currentRunningTrem.yb.ToString(), teamOne, teamTwo, teamThree, teamFour);
                    for (int i = 0; i < drybStationDriver.Length; i++)
                    {
                        int index = FindCrossingRoadIndex(drybStationCrossingRoad, drybStationDriver[i]["dcom_grp_type"].ToString());
                        if (index != -1)
                        {

                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybStationDriver[i], drTableTimeInfo[0], drybStationCrossingRoad[index], de, "3", ref dtEmptyDriverCombine);

                            #region
                            //增加进夜班表

                            DataRow dr = dtYBoffInfo.NewRow();
                            dr[0] = drybStationDriver[i]["ID"].ToString();
                            dr[1] = drybStationDriver[i]["dcom_grp_type"].ToString();
                            dr[2] = currentRunningTrem.zb;
                            dr[3] = drybStationDriver[i]["dcom_dutynum"].ToString();
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_opdriver"].ToString()))
                            {
                                dr[5] = drybStationDriver[i]["dcom_opdriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriver"].ToString()))
                            {
                                dr[6] = drybStationDriver[i]["dcom_monidriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriverTwo"].ToString()))
                            {
                                dr[7] = drybStationDriver[i]["dcom_monidriverTwo"].ToString();

                            }
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriverThree"].ToString()))
                            {
                                dr[10] = drybStationDriver[i]["dcom_monidriverThree"].ToString();
                                //dcom_monidriverThree
                            }
                            if (Convert.ToDateTime(drybStationCrossingRoad[index]["offTime"].ToString()) < Convert.ToDateTime(drybStationCrossingRoad[index]["attenTime"].ToString()))
                            {
                                dr[4] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybStationCrossingRoad[index]["offTime"].ToString();
                            }
                            else
                            {
                                dr[4] = de.Key.ToString() + " " + drybStationCrossingRoad[index]["offTime"].ToString();
                            }
                            if (string.IsNullOrEmpty(drybStationCrossingRoad[index]["lastTrainTime"].ToString()))
                            {
                                dr[8] = DBNull.Value;
                            }
                            else
                            {
                                if (Convert.ToDateTime(drybStationCrossingRoad[index]["lastTrainTime"].ToString()) < Convert.ToDateTime(drybStationCrossingRoad[index]["attenTime"].ToString()))
                                {
                                    dr[8] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybStationCrossingRoad[index]["lastTrainTime"].ToString();
                                }
                                else
                                {
                                    dr[8] = de.Key.ToString() + " " + drybStationCrossingRoad[index]["lastTrainTime"].ToString();
                                }
                            }

                            //dr[8] = DBNull.Value;
                            dr[9] = drybStationDriver[i]["dcom_NO"].ToString();
                            dtYBoffInfo.Rows.Add(dr);
                            #endregion
                        }
                        else
                        {
                            AddRowInDriverCombineCrossingRoadPlane(ref dtDriverCombineCrossingRoadPlane, currentRunningTrem.yb, drybStationDriver[i], drTableTimeInfo[0], null, de, "3", ref dtEmptyDriverCombine);

                            #region

                            DataRow dr = dtYBoffInfo.NewRow();
                            dr[0] = drybStationDriver[i]["ID"].ToString();
                            dr[1] = drybStationDriver[i]["dcom_grp_type"].ToString();
                            dr[2] = currentRunningTrem.zb;
                            dr[3] = drybStationDriver[i]["dcom_dutynum"].ToString();
                            dr[4] = DBNull.Value;
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_opdriver"].ToString()))
                            {
                                dr[5] = drybStationDriver[i]["dcom_opdriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriver"].ToString()))
                            {
                                dr[6] = drybStationDriver[i]["dcom_monidriver"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriverTwo"].ToString()))
                            {
                                dr[7] = drybStationDriver[i]["dcom_monidriverTwo"].ToString();
                            }
                            if (!string.IsNullOrEmpty(drybStationDriver[i]["dcom_monidriverThree"].ToString()))
                            {
                                dr[10] = drybStationDriver[i]["dcom_monidriverThree"].ToString();
                            }
                            //if (string.IsNullOrEmpty(drybStationCrossingRoad[i]["lastTrainTime"].ToString()))
                            //{
                            dr[8] = DBNull.Value;
                            //}
                            //else
                            //{
                            //    if (Convert.ToDateTime(drybStationCrossingRoad[i]["lastTrainTime"].ToString()) < Convert.ToDateTime(drybStationCrossingRoad[i]["attenTime"].ToString()))
                            //    {
                            //        dr[8] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + drybStationCrossingRoad[i]["lastTrainTime"].ToString();
                            //    }
                            //    else
                            //    {
                            //        dr[8] = de.Key.ToString() + " " + drybStationCrossingRoad[i]["lastTrainTime"].ToString();
                            //    }
                            //}
                            dr[9] = drybStationDriver[i]["dcom_NO"].ToString();
                            dtYBoffInfo.Rows.Add(dr);
                            #endregion
                        }
                    }
                    //夜班按退勤时间排序


                }
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("====================交路分配司机结束==========================");
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("====================开始将数据写入数据库==========================");
                //写入数据库
                //先清除所有调班记录

                //查找出调班时间和还班时间在这个时间段内的信息
                DataTable dtSwr = _teamAccess.GetSwitchRecordByMonth(Convert.ToDateTime(startDay).AddDays(-1).ToString("yyyy-MM-dd"), endDay);
                //查找出需要取消还班的(并且日期申请日期大于重轮日期) 这些是用于取消的
                DataRow[] drsCancelBack = dtSwr.Select("sr_chgdate>'" + endDay + "' and sr_appdate<'" + Convert.ToDateTime(startDay).AddDays(-1).ToString("yyyy-MM-dd") + "'");
                //查找出需要取消调班的
                DataRow[] drsCancelAll = dtSwr.Select("sr_appdate>='" + Convert.ToDateTime(startDay).AddDays(-1).ToString("yyyy-MM-dd") + "' and sr_appdate<='" + endDay + "'", "ID asc");

                //提示有哪些调班记录会被取消还班
                //ArrayList al = new ArrayList();
                //foreach (DataRow drSwr in drsCancelBack)
                //{
                //    al.Add(drSwr["appUserName"].ToString() + "与" + drSwr["chagUserName"].ToString() + " " + drSwr["sr_chgdate"].ToString());
                //}
                //if (al.Count > 0)
                //{
                //    al.Insert(0, "以下调班将被取消调班");
                //}


                DataTable dtRemark = _teamAccess.GetSourceRemarkNew(startDay, endDay);
                //开启事务
                tranId = sqlHelper.OpenNewTransaction();

                //提醒那些信息会被取消还班


                if (IsKeepSwr)
                {
                    //取消调班记录
                    foreach (DataRow drSwr in drsCancelAll)
                    {
                        int i = 0;
                        try
                        {
                            if (drSwr[0].ToString() == "2733")
                            {
                                MessageBox.Show("");
                            }
                            ArrayList lst = new ArrayList();
                            CancelExchangeDriverNew(drSwr["sr_applicant"].ToString(), drSwr["sr_appdate"].ToString(), ref lst, tranId);
                            sqlHelper.ExecuteSqlTran(lst, tranId);
                        }
                        catch
                        {
                            MessageBox.Show("");
                            if (!string.IsNullOrEmpty(tranId))
                                sqlHelper.RollbackTransaction(tranId);
                            // MessageBoxHelper.ShowError("轮班失败" + ex.Message);

                            return false;
                        }

                    }
                    //取消还班记录
                    foreach (DataRow drSwr in drsCancelBack)
                    {
                        ArrayList lst = new ArrayList();
                        CancelBackExchangeDriver(drSwr["sr_applicant"].ToString(), drSwr["sr_appdate"].ToString(), ref lst, tranId);
                        sqlHelper.ExecuteSqlTran(lst, tranId);
                    }

                    _teamAccess.RevertRemarkNew(dtRemark, dtDriverCombineCrossingRoadPlane);
                }
                else
                {
                    //取消还班
                    foreach (DataRow drSwr in drsCancelBack)
                    {
                        ArrayList lst = new ArrayList();
                        CancelBackExchangeDriver(drSwr["sr_applicant"].ToString(), drSwr["sr_appdate"].ToString(), ref lst, tranId);
                        sqlHelper.ExecuteSqlTran(lst, tranId);
                    }
                    //删除掉所有调班记录
                    //  _teamAccess.delSwitch(startDay, endDay, tranId);
                    _teamAccess.delSwitch(startDay, tranId);
                }
                //
                //清除掉超过结束日期的所有调班
                _teamAccess.delSwitch(endDay, tranId);
                //清除数据库开始日期之后的数据
                _teamAccess.DelPlan(startDay, tranId);
                //轮班
                _teamAccess.SetClassTurnPlane(dtClassTrunPlane, tranId);
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入ClassTurnPlane");
                //插入计划司机
                _teamAccess.SetDriverCombine(dtEmptyDriverCombine, tranId);
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入DriverCombine");
                //周月计划


                _teamAccess.SetDriverCombineCrossingRoadPlane(dtDriverCombineCrossingRoadPlane, tranId);
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入dtDriverCombineCrossingRoadPlane");
                //写入计划
                if (isNewClassPlaneRec == false)
                {
                    _teamAccess.UpdateClassTurnPlaneRecord(startDay, tranId);
                    _teamAccess.AddClassTurnPlaneRecord(startDay, endDay, tranId);
                }
                else
                {

                    _teamAccess.UpdateClassTurnPlaneRecordBySame(endDay, tranId);
                }
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("写入ClassTurnPlaneRecord");


                //把基础数据更改为最后一天的的数据
                DateTime endTime = Convert.ToDateTime(endDay);
                _teamAccess.UpdateDriver(endTime.Year.ToString() + "-" + endTime.Month.ToString() + "-" + endTime.Day, tranId);
                //重新进行一次调班
                if (IsKeepSwr)
                {

                    foreach (DataRow drSwr in drsCancelAll)
                    {

                        DataTable dtcmbAppCls = GetCrsInfoByUseId(drSwr["sr_SouceApplicant"].ToString(), drSwr["sr_appdate"].ToString(), tranId);
                        DataTable dtcmbTAppcls = GetCrsInfoByUseId(drSwr["sr_SouceChanger"].ToString(), drSwr["sr_appdate"].ToString(), tranId);

                        string strAppBackcls = "";
                        string strTAppBackcls = "";
                        string chgdate = "";
                        if (!string.IsNullOrEmpty(drSwr["sr_chgdate"].ToString()))
                        {
                            if (Convert.ToDateTime(drSwr["sr_chgdate"].ToString()) <= Convert.ToDateTime(endDay))
                            {
                                DataTable dtstrAppBackcls = GetCrsInfoByUseId(drSwr["sr_SouceApplicant"].ToString(), drSwr["sr_chgdate"].ToString(), tranId);
                                DataTable dtstrTAppBackcls = GetCrsInfoByUseId(drSwr["sr_SouceChanger"].ToString(), drSwr["sr_chgdate"].ToString(), tranId);
                                strAppBackcls = dtstrAppBackcls.Rows[0][0].ToString();
                                strTAppBackcls = dtstrTAppBackcls.Rows[0][0].ToString();

                                chgdate = drSwr["sr_chgdate"].ToString();
                            }
                        }


                        if (dtcmbAppCls.Rows.Count > 0 && dtcmbTAppcls.Rows.Count > 0)
                        {
                            ExchangeDriverNew(dtcmbAppCls.Rows[0][0].ToString(), dtcmbTAppcls.Rows[0][0].ToString(), strAppBackcls, strTAppBackcls, drSwr["sr_appdate"].ToString(), chgdate, drSwr["sr_reason"].ToString(), drSwr["sr_applicant"].ToString(), drSwr["sr_changer"].ToString(), tranId);
                        }

                    }
                }


                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("更新基础司机表的序号");
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("====================将数据写入数据库结束==========================");
                sqlHelper.CommitTransaction(tranId);
                return true;
            }
            catch (Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError("轮班逻辑失败" + ex.ToString());
                if (!string.IsNullOrEmpty(tranId))
                    sqlHelper.RollbackTransaction(tranId);
                // MessageBoxHelper.ShowError("轮班失败" + ex.Message);

                return false;
            }

        }

        //判断是否需要写入新的轮班计划

        public bool isNewclassPlane(string stareday)
        {
            DataTable dt = _teamAccess.GetDriverCombineToChkClassPlane();
            DataTable dt2 = _teamAccess.GetDriverCombineToChkClassPlaneBydate(stareday);

            return DataTableTheSame(dt, dt2);
        }

        /// <summary>
        /// 比较两个datatable是否相同
        /// </summary>
        /// <param name="Table1"></param>
        /// <param name="Table2"></param>
        /// <returns></returns>
        public bool DataTableTheSame(DataTable Table1, DataTable Table2)
        {
            if (Table1 == null || Table2 == null)
            {
                return false;
            }
            if (Table1.Rows.Count != Table2.Rows.Count)
            {
                return false;
            }
            if (Table1.Columns.Count != Table2.Columns.Count)
            {
                return false;
            }
            for (int i = 0; i < Table1.Rows.Count; i++)
            {
                for (int j = 0; j < Table1.Columns.Count; j++)
                {
                    if (Table1.Rows[i][j].ToString() != Table2.Rows[i][j].ToString())
                    {
                        return false;
                    }
                }
            }
            return true;
        }


        /// <summary>
        /// 获取上个月的月排班人员
        /// </summary>
        /// <param name="dtPlane"></param>
        /// <param name="date"></param>
        /// <param name="team"></param>
        /// <returns></returns>
        public string GetLastMonthYBBDriver(DataTable dtPlane, string date, string team)
        {
            //先查询内存里面有没有月备班信息，有的话拿出来
            DateTime dtThisMonth = Convert.ToDateTime(date);
            DateTime dtLastMonth = dtThisMonth.AddMonths(-1);
            int day = DateTime.DaysInMonth(dtLastMonth.Year, dtLastMonth.Month);
            date = dtLastMonth.Year.ToString() + "-" + dtLastMonth.Month.ToString() + "-" + day.ToString();
            // date=Convert.ToDateTime(date).Month
            DataRow[] drs = dtPlane.Select("dcdr_date='" + date + "' and dcdr_team='" + team + "' and dcdr_driverType=6");
            if (drs.Length > 0)
            {
                return drs[0]["dcdr_driverCombineId"].ToString();
            }
            else
            {
                DataTable dt = _teamAccess.GetDtYBBDriver(date, team);
                if (dt.Rows.Count > 0)
                {
                    return dt.Rows[0][0].ToString();
                }
            }


            //再查询数据库有没有这月备班信息，有的话拿出来
            return "";

        }
        /// <summary>
        /// 获取轮班情况
        /// </summary>
        /// <returns></returns>
        //public DataTable GetLastClassTrun()
        //{
        //    DataTable dtLastClassTrue = _teamAccess.GetLastClass();
        //    return dtLastClassTrue;

        //}

        /// <summary>
        /// 开始轮班
        /// </summary>
        /// <param name="dtClassTruePlane">轮班表</param>
        /// <param name="zb">早班</param>
        /// <param name="xb">休班</param>
        /// <param name="bb">白班</param>
        /// <param name="yb">夜班</param>
        public void TrunClass(ref DataTable dtClassTruePlane, ref CurrentRunningTrem runningTeam, string date)
        {
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("进行轮班");
            //先轮,后插
            //轮
            int teamzb = runningTeam.zb;
            int teamxb = runningTeam.xb;
            int teambb = runningTeam.bb;
            int teamyb = runningTeam.yb;
            runningTeam.zb = teamyb;
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("早班" + teamyb.ToString());
            runningTeam.xb = teamzb;
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("休班" + teamzb.ToString());
            runningTeam.bb = teamxb;
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("白班" + teamxb.ToString());
            runningTeam.yb = teambb;
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("晚班" + teamxb.ToString());
            //插
            DataRow drteamOne = dtClassTruePlane.NewRow();
            drteamOne[1] = line.ToString();
            drteamOne[2] = "1";
            drteamOne[3] = FindClassByTeam("1", runningTeam).ToString();
            drteamOne[4] = date;
            dtClassTruePlane.Rows.Add(drteamOne);
            DataRow drteamTwo = dtClassTruePlane.NewRow();
            drteamTwo[1] = line.ToString();
            drteamTwo[2] = "2";
            drteamTwo[3] = FindClassByTeam("2", runningTeam).ToString();
            drteamTwo[4] = date;
            dtClassTruePlane.Rows.Add(drteamTwo);
            DataRow drteamThree = dtClassTruePlane.NewRow();
            drteamThree[1] = line.ToString();
            drteamThree[2] = "3";
            drteamThree[3] = FindClassByTeam("3", runningTeam).ToString();
            drteamThree[4] = date;
            dtClassTruePlane.Rows.Add(drteamThree);
            DataRow drteamFour = dtClassTruePlane.NewRow();
            drteamFour[1] = line.ToString();
            drteamFour[2] = "4";
            drteamFour[3] = FindClassByTeam("4", runningTeam).ToString();
            drteamFour[4] = date;
            dtClassTruePlane.Rows.Add(drteamFour);


        }

        /// <summary>
        /// 通过组号查找当前班次
        /// </summary>
        /// <param name="team"></param>
        /// <returns></returns>
        public int FindClassByTeam(string team, CurrentRunningTrem runningTeam)
        {
            if (runningTeam.zb.ToString() == team)
            {
                return 0;
            }
            if (runningTeam.xb.ToString() == team)
            {
                return 1;
            }
            if (runningTeam.bb.ToString() == team)
            {
                return 2;
            }
            if (runningTeam.yb.ToString() == team)
            {
                return 3;
            }
            return -1;

        }

        /// <summary>
        /// 初始化当前班次
        /// </summary>
        /// <param name="dtClassTrun"></param>
        /// <returns></returns>
        public CurrentRunningTrem InitRunningTrem(DataTable dtClassTrun)
        {
            CurrentRunningTrem currentRuningTrem = new CurrentRunningTrem();
            DataRow[] drzb = dtClassTrun.Select("ctn_cls_id=0");
            DataRow[] drxb = dtClassTrun.Select("ctn_cls_id=1");
            DataRow[] drbb = dtClassTrun.Select("ctn_cls_id=2");
            DataRow[] dryb = dtClassTrun.Select("ctn_cls_id=3");
            if (drbb.Length > 0 && drzb.Length > 0 && drxb.Length > 0 && dryb.Length > 0)
            {
                currentRuningTrem.zb = Convert.ToInt32(drzb[0]["ctn_team"].ToString());
                currentRuningTrem.xb = Convert.ToInt32(drxb[0]["ctn_team"].ToString());
                currentRuningTrem.bb = Convert.ToInt32(drbb[0]["ctn_team"].ToString());
                currentRuningTrem.yb = Convert.ToInt32(dryb[0]["ctn_team"].ToString());
            }
            else
            {
                InitializationClass initial = new InitializationClass(ref currentRuningTrem)
 ;
                initial.ShowDialog();


            }
            return currentRuningTrem;
        }

        /// <summary>
        /// 查找车场人员在队伍的位置
        /// </summary>
        /// <param name="dtDriveCombine"></param>
        /// <param name="team"></param>
        /// <returns></returns>
        public TeamStationIndex SetTeamStationIndex(DataTable dtDriveCombine, string team)
        {
            TeamStationIndex teamStationIndex = new TeamStationIndex();
            DataRow[] drrb = dtDriveCombine.Select("dcom_grp_type=1 and dcom_team='" + team + "'");
            if (drrb.Length > 0)
            {
                teamStationIndex.rb = Convert.ToInt32(drrb[0]["dcom_dutynum"]);
            }
            DataRow[] drdc = dtDriveCombine.Select("dcom_grp_type=2 and dcom_team='" + team + "'");
            if (drdc.Length > 0)
            {
                teamStationIndex.dcx = Convert.ToInt32(drdc[0]["dcom_dutynum"]);
            }

            DataRow[] drscx = dtDriveCombine.Select("dcom_grp_type=3 and dcom_team='" + team + "'");
            if (drscx.Length > 0)
            {
                teamStationIndex.scx = Convert.ToInt32(drscx[0]["dcom_dutynum"]);
            }

            DataRow[] drbb = dtDriveCombine.Select("dcom_grp_type=4 and dcom_team='" + team + "'");
            if (drbb.Length > 0)
            {
                teamStationIndex.bb = Convert.ToInt32(drbb[0]["dcom_dutynum"]);
            }
            DataRow[] drybb = dtDriveCombine.Select("dcom_grp_type=6 and dcom_team='" + team + "'");
            if (drybb.Length > 0)
            {
                //teamStationIndex.ybb = Convert.ToInt32(drybb[0]["dcom_dutynum"]);
                foreach (var dataRow in drybb)
                {
                    teamStationIndex.ybb.Add(Convert.ToInt32(dataRow["dcom_dutynum"]));
                }

            }
            DataRow[] drsjz = dtDriveCombine.Select("dcom_grp_type=7 and dcom_team='" + team + "'");
            if (drsjz.Length > 0)
            {
                teamStationIndex.sjz = Convert.ToInt32(drsjz[0]["dcom_dutynum"]);
            }

            DataRow[] drddy = dtDriveCombine.Select("dcom_grp_type=8 and dcom_team='" + team + "'");
            if (drddy.Length > 0)
            {
                teamStationIndex.ddy = Convert.ToInt32(drddy[0]["dcom_dutynum"]);
            }

            return teamStationIndex;



        }

        public Hashtable GetHstMonthsBB(DataTable dtDriveCombine)
        {
            Hashtable hst = new Hashtable();
            DataRow[] drs = dtDriveCombine.Select("dcom_grp_type=6");
            foreach (DataRow dr in drs)
            {
                hst.Add(dr["dcom_team"].ToString(), dr["ID"].ToString());
            }
            return hst;
        }

        public TeamStationIndex FindTeamStationIndex(string team, TeamStationIndex one, TeamStationIndex two, TeamStationIndex three, TeamStationIndex four)
        {
            TeamStationIndex teamStationIndex = new TeamStationIndex();
            if (team == "1")
            { teamStationIndex = one; }
            else if (team == "2")
            { teamStationIndex = two; }
            else if (team == "3")
            { teamStationIndex = three; }
            else if (team == "4")
            { teamStationIndex = four; }
            return teamStationIndex;
        }

        public int FindCrossingRoadIndex(DataRow[] drs, string type)
        {
            int index = -1;
            foreach (DataRow dr in drs)
            {
                index++;
                if (dr["grp_id"].ToString() == type)
                {
                    return index;
                }

            }

            return -1;
        }

        public string GetDriveType(string type)
        {
            if (type == "1")
            {
                return "热备";
            }
            else if (type == "2")
            {
                return "调车";
            }
            else if (type == "3")
            {
                return "试车线";
            }
            else if (type == "4")
            {
                return "备班";
            }
            else if (type == "5")
            {
                return "";
            }
            else if (type == "6")
            {
                return "月备班";
            }
            else if (type == "7")
            {
                return "司机长";
            }
            return "异常";
        }

        public string GetZBYName(string type)
        {
            if (type == "0")
            {
                return "早班";
            }
            else if (type == "2")
            {
                return "白班";
            }
            else if (type == "3")
            {
                return "晚班";
            }
            else if (type == "1")
            {
                return "休班";
            }


            return "异常";
        }

        public Hashtable GetTableNameWithDate(int year, int month)
        {
            Hashtable hasTbleNameWithDate = new Hashtable();
            List<string> lstNoSetDay = new List<string>();
            //获取这一整个月的排班表信息
            DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimetable(year, month);
            int daysInMonth = DateTime.DaysInMonth(year, month);

            for (int i = 1; i <= daysInMonth; i++)
            {
                //查找数据库看这一天有没有设置排班排班表
                string fiter = "AssignDate=" + "'" + year.ToString() + "-" + month.ToString().PadLeft(2, '0') + "-" + i.ToString().PadLeft(2, '0') + "'"; //筛选条件
                string days = year.ToString() + "-" + month.ToString().PadLeft(2, '0') + "-" + i.ToString().PadLeft(2, '0');
                DataRow[] drs = dtMonthTimeTable.Select(fiter);

                //获取每天对应的交路表
                hasTbleNameWithDate.Add(days, drs[0][1].ToString());
            }

            return hasTbleNameWithDate;
        }


        public Hashtable GetTableNameWithDate(int year, int month, int startday, int endday)
        {
            Hashtable hasTbleNameWithDate = new Hashtable();
            List<string> lstNoSetDay = new List<string>();
            //获取这一整个月的排班表信息
            DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimetable(year, month);
            int daysInMonth = DateTime.DaysInMonth(year, month);

            for (int i = startday; i <= endday; i++)
            {
                //查找数据库看这一天有没有设置排班排班表
                string fiter = "AssignDate=" + "'" + year.ToString() + "-" + month.ToString().PadLeft(2, '0') + "-" + i.ToString().PadLeft(2, '0') + "'"; //筛选条件
                string days = year.ToString() + "-" + month.ToString().PadLeft(2, '0') + "-" + i.ToString().PadLeft(2, '0');
                DataRow[] drs = dtMonthTimeTable.Select(fiter);

                //获取每天对应的交路表
                hasTbleNameWithDate.Add(days, drs[0][1].ToString());
            }

            return hasTbleNameWithDate;
        }

        public Hashtable GetTableNameWithDate(string startDay, string endDay)
        {
            Hashtable hasTbleNameWithDate = new Hashtable();
            List<string> lstNoSetDay = new List<string>();
            //获取这一整个月的排班表信息
            DataTable dtMonthTimeTable = _teamAccess.GetDtMonthTimetable(startDay, endDay);
            // int daysInMonth = DateTime.DaysInMonth(year, month);
            DateTime dtStart = Convert.ToDateTime(startDay);
            DateTime dtend = Convert.ToDateTime(endDay);
            DateTime dtTemp = dtStart;

            while (dtTemp <= dtend)
            {
                string fiter = "AssignDate=" + "'" + dtTemp.Year.ToString() + "-" + dtTemp.Month.ToString().PadLeft(2, '0') + "-" + dtTemp.Day.ToString().PadLeft(2, '0') + "'"; //筛选条件
                string days = dtTemp.Year.ToString() + "-" + dtTemp.Month.ToString().PadLeft(2, '0') + "-" + dtTemp.Day.ToString().PadLeft(2, '0');
                DataRow[] drs = dtMonthTimeTable.Select(fiter);

                //获取每天对应的交路表
                hasTbleNameWithDate.Add(days, drs[0][1].ToString());

                dtTemp = dtTemp.AddDays(1);

            }

            return hasTbleNameWithDate;
        }


        public DataTable GetDriverCombineCrossingRoadPlane(int year, int month)
        {
            return _teamAccess.GetDriverCombineCrossingRoadPlane(year, month);
        }

        public DataTable GetDriverCombineCrossingRoadPlane(int year, int month, int startDay, int endDay)
        {
            return _teamAccess.GetDriverCombineCrossingRoadPlane(year, month, startDay, endDay);
        }

        public DataTable GetDriverCombineCrossingRoadPlane(string startDay, string endDay)
        {
            return _teamAccess.GetDriverCombineCrossingRoadPlane(startDay, endDay);
        }

        public void UpdateDriverCombineCrossingRoadPlaneRemark(Dictionary<string, string> dic)
        {
            _teamAccess.UpdateDriverCombineCrossingRoadPlaneRemark(dic);
        }

        public DataTable GetClassTurnPlaneRecord()
        {
            return _teamAccess.GetClassTurnPlaneRecord();
        }

        private void InitAllDriver()
        {
            DicDriverInfo.Clear();
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("初始化所有司机");
            // string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = " + lineid + " order by user_view_name";
            DataTable driverDT = _teamAccess.GetDtDriverInfo();
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDT.Rows[i]["user_id"].ToString());

                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo(id.ToString() + " " + driver.userName + driver.userViewName);
                    DicDriverInfo.Add(id, driver);
                }
            }

        }

        public string GetUserViewNameByID(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return "";
            }
            int ID = Convert.ToInt32(id);
            string result = "";
            Driver driver = null;
            if (DicDriverInfo.TryGetValue(ID, out driver))
            {
                result = driver.userViewName;
            }

            return result;
        }

        /// <summary>
        /// 插入月计划表
        /// </summary>
        /// <param name="dt">月计划表</param>
        /// <param name="currentRunningTrem">轮转顺序</param>
        /// <param name="drDriver">司机信息</param>
        /// <param name="drTableInfo">时刻表</param>
        /// <param name="drCrossingRoad">交路信息</param>
        /// <param name="de">今天所用时刻表</param>
        /// <param name="classes">班次</param>
        /// <param name="type">类型</param>
        public void AddRowInDriverCombineCrossingRoadPlane(ref DataTable dt, int currentRunningTrem, DataRow drDriver, DataRow drTableInfo, DataRow drCrossingRoad, KeyValuePair<string, string> de, string classes, ref DataTable dtDriver)
        {
            AddRowInDriverCombineCrossingRoadPlane(ref dt, currentRunningTrem, drDriver, drTableInfo, drCrossingRoad, de, classes, "1");
            AddRowInDriverCombineCrossingRoadPlane(ref dt, currentRunningTrem, drDriver, drTableInfo, drCrossingRoad, de, classes, "2");
            AddRowInDriverCombineCrossingRoadPlane(ref dt, currentRunningTrem, drDriver, drTableInfo, drCrossingRoad, de, classes, "3");
            AddRowInDriverCombineCrossingRoadPlane(ref dt, currentRunningTrem, drDriver, drTableInfo, drCrossingRoad, de, classes, "4");
            //写入司机组合表
            AddDriverCombine(ref dtDriver, currentRunningTrem, drDriver, drCrossingRoad, de);

        }

        public string GetDriverTypeByCross(DataRow drCrossingRoad)
        {
            if (null != drCrossingRoad)
            {
                return GetDriveType(drCrossingRoad["grp_id"].ToString());
            }
            else
            {
                return "休";
            }

        }

        public void AddRowInDriverCombineCrossingRoadPlane(ref DataTable dt, int currentRunningTrem, DataRow drDriver, DataRow drTableInfo, DataRow drCrossingRoad, KeyValuePair<string, string> de, string classes, string type)
        {
            string classesName = GetZBYName(classes).Substring(0, 1);
            string remark = GetDriverTypeByCross(drCrossingRoad);
            DataRow drplane = dt.NewRow();
            drplane["line"] = line;
            drplane["dcdr_team"] = currentRunningTrem;
            drplane["dcdr_date"] = de.Key.ToString();
            drplane["dcdr_cls_id"] = classes;
            drplane["dcdr_driverCombineId"] = drDriver[0].ToString();
            drplane["dcdr_driverType"] = drDriver[1].ToString(); ;
            drplane["dcdr_tableTimeid"] = drTableInfo["ID"]; ;
            drplane["dcdr_tableTimeName"] = de.Value.ToString();
            drplane["dcdr_driverCombineId"] = drDriver[0].ToString();
            drplane["dcdr_dutyNum"] = drDriver[3].ToString();

            if (!string.IsNullOrEmpty(drDriver["dcom_opdriver"].ToString()))
            {
                drplane["dcom_opdriver"] = drDriver["dcom_opdriver"].ToString();
            }
            if (!string.IsNullOrEmpty(drDriver["dcom_monidriver"].ToString()))
            {
                drplane["dcom_monidriver"] = drDriver["dcom_monidriver"].ToString();
            }
            if (!string.IsNullOrEmpty(drDriver["dcom_monidriverTwo"].ToString()))
            {
                drplane["dcom_monidriverTwo"] = drDriver["dcom_monidriverTwo"].ToString();
            }
            drplane["dcom_NO"] = drDriver["dcom_NO"].ToString();
            drplane["dcom_opdriverName"] = GetUserViewNameByID(drDriver["dcom_opdriver"].ToString());
            drplane["dcom_monidriverName"] = GetUserViewNameByID(drDriver["dcom_monidriver"].ToString());
            drplane["dcom_monidriverNameTwo"] = GetUserViewNameByID(drDriver["dcom_monidriverTwo"].ToString());
            if (drCrossingRoad != null)
            {
                drplane["dcdr_crossid"] = drCrossingRoad["ID"].ToString();
                drplane["dcdr_crossNum"] = drCrossingRoad["number"].ToString();
                drplane["dcdr_crossAttenPlace"] = drCrossingRoad["attenPlace"].ToString();
                drplane["dcdr_crossAttenTime"] = drCrossingRoad["attenTime"].ToString();
                drplane["dcdr_crossoffTime"] = drCrossingRoad["offTime"].ToString();
                drplane["dcdr_crossoffPlace"] = drCrossingRoad["offPlace"].ToString();
                drplane["dcdr_remark"] = classesName + drCrossingRoad["number"].ToString() + " " + remark + " " + drplane["dcdr_crossAttenPlace"].ToString() + ":" + drplane["dcdr_crossAttenTime"].ToString();
                drplane["dcdr_duty"] = drCrossingRoad["CrName"].ToString();
                drplane["dcdr_crosszby"] = drCrossingRoad["zby"].ToString();
                drplane["dcdr_crosstype"] = drCrossingRoad["grp_id"].ToString();
                if (string.IsNullOrEmpty(drCrossingRoad["miles"].ToString()))
                {
                    drplane["miles"] = "0";
                    drplane["sourcemiles"] = "0";
                }
                else
                {
                    drplane["miles"] = drCrossingRoad["miles"].ToString();
                    drplane["sourcemiles"] = drCrossingRoad["miles"].ToString();
                }

                if (string.IsNullOrEmpty(drCrossingRoad["wHours"].ToString()))
                {
                    drplane["wHours"] = "0";
                    drplane["sourcewHours"] = "0";
                }
                else
                {
                    drplane["wHours"] = drCrossingRoad["wHours"].ToString();
                    drplane["sourcewHours"] = drCrossingRoad["wHours"].ToString();
                }


                if (classes == "3")
                {
                    if (!string.IsNullOrEmpty(drCrossingRoad["offSeq"].ToString()))
                    {
                        drplane["dcdr_ybarrive"] = Convert.ToInt32(drCrossingRoad["offSeq"]);
                    }
                    else
                    {
                        drplane["dcdr_ybarrive"] = 0;
                    }
                }
            }
            else
            {
                if (classes == "1")
                {
                    drplane["dcdr_crossid"] = 0;
                    drplane["dcdr_remark"] = classesName;
                    drplane["dcdr_duty"] = classesName;
                }
                else
                {
                    drplane["dcdr_crossid"] = -1;
                    drplane["dcdr_remark"] = "休（" + classesName + ")";
                    drplane["dcdr_duty"] = "休（" + classesName + ")";
                    drplane["dcdr_crossNum"] = -1;
                }
                if (classes == "3")
                {
                    drplane["dcdr_ybarrive"] = "0";
                }


            }
            //修改为增加两条记录 一条副司机 一条主司机
            if (type == "1") //1代表主司机
            {
                if (!string.IsNullOrEmpty(drDriver["dcom_opdriver"].ToString()))
                {
                    DataRow drOpdriver = dt.NewRow();
                    drOpdriver.ItemArray = drplane.ItemArray;
                    drOpdriver["dcdr_userID"] = drDriver["dcom_opdriver"].ToString();
                    drOpdriver["dcdr_userName"] = GetUserViewNameByID(drDriver["dcom_opdriver"].ToString());
                    drOpdriver["dcdr_type"] = 1;
                    dt.Rows.Add(drOpdriver);
                }
            }
            if (type == "2")//2代表副司机
            {
                if (!string.IsNullOrEmpty(drDriver["dcom_monidriver"].ToString()))
                {
                    DataRow drMonidriver = dt.NewRow();
                    drMonidriver.ItemArray = drplane.ItemArray;
                    drMonidriver["dcdr_userID"] = drDriver["dcom_monidriver"].ToString();
                    drMonidriver["dcdr_userName"] = GetUserViewNameByID(drDriver["dcom_monidriver"].ToString());
                    drMonidriver["dcdr_type"] = 2;
                    dt.Rows.Add(drMonidriver);
                }
            }
            if (type == "3")//2代表监控司机
            {
                if (!string.IsNullOrEmpty(drDriver["dcom_monidriverTwo"].ToString()))
                {
                    DataRow drMonidriverTwo = dt.NewRow();
                    drMonidriverTwo.ItemArray = drplane.ItemArray;
                    drMonidriverTwo["dcdr_userID"] = drDriver["dcom_monidriverTwo"].ToString();
                    drMonidriverTwo["dcdr_userName"] = GetUserViewNameByID(drDriver["dcom_monidriverTwo"].ToString());
                    drMonidriverTwo["dcdr_type"] = 3;
                    dt.Rows.Add(drMonidriverTwo);
                }
            }
            if (type == "4")//2代表监控司机
            {
                if (!string.IsNullOrEmpty(drDriver["dcom_monidriverThree"].ToString()))
                {
                    DataRow drMonidriverTwo = dt.NewRow();
                    drMonidriverTwo.ItemArray = drplane.ItemArray;
                    drMonidriverTwo["dcdr_userID"] = drDriver["dcom_monidriverThree"].ToString();
                    drMonidriverTwo["dcdr_userName"] = GetUserViewNameByID(drDriver["dcom_monidriverThree"].ToString());
                    drMonidriverTwo["dcdr_type"] = 4;
                    dt.Rows.Add(drMonidriverTwo);
                }
            }

        }

        public void AddDriverCombine(ref DataTable dtCombine, int currentRunningTrem, DataRow drDriver, DataRow drCrossingRoad, KeyValuePair<string, string> de)
        {

            DataRow dr = dtCombine.NewRow();
            dr["dcom_lineid"] = line;
            dr["dcom_team"] = currentRunningTrem;
            dr["dcom_dutynum"] = drDriver[3].ToString();
            //dr["dcom_NO"] = drDriver["dcom_NO"].ToString();
            if (!string.IsNullOrEmpty(drDriver["dcom_opdriver"].ToString()))
            {
                dr["dcom_opdriver"] = drDriver["dcom_opdriver"].ToString();
            }
            else
            { dr["dcom_opdriver"] = DBNull.Value; }
            if (!string.IsNullOrEmpty(drDriver["dcom_monidriver"].ToString()))
            {
                dr["dcom_monidriver"] = drDriver["dcom_monidriver"].ToString();
            }
            else
            {
                dr["dcom_monidriver"] = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(drDriver["dcom_monidriverTwo"].ToString()))
            {
                dr["dcom_monidriverTwo"] = drDriver["dcom_monidriverTwo"].ToString();
            }
            else
            {
                dr["dcom_monidriverTwo"] = DBNull.Value;
            }

            if (!string.IsNullOrEmpty(drDriver["dcom_monidriverThree"].ToString()))
            {
                dr["dcom_monidriverThree"] = drDriver["dcom_monidriverThree"].ToString();
            }
            else
            {
                dr["dcom_monidriverThree"] = DBNull.Value;
            }

            if (drCrossingRoad != null)
            {
                dr["dcom_cr_number"] = drCrossingRoad["ID"].ToString();
                if (!string.IsNullOrEmpty(drCrossingRoad["offSeq"].ToString()))
                {
                    dr["dcom_ybarrive"] = drCrossingRoad["offSeq"].ToString();
                }
            }



            dr["dcom_grp_type"] = drDriver[1].ToString(); ;
            dr["dcom_date"] = de.Key.ToString();
            dr["dcom_parents"] = Convert.ToInt32(drDriver[0].ToString());
            dr["dcom_NO"] = Convert.ToInt32(drDriver["dcom_NO"].ToString());
            dtCombine.Rows.Add(dr);

        }


        public void setCrossingRoadOffTime(ref DataTable dtCrossingRoad, KeyValuePair<string, string> de)
        {

            foreach (DataRow dr in dtCrossingRoad.Rows)
            {
                try
                {
                    if (Convert.ToDateTime(dr["offTime"].ToString()) < Convert.ToDateTime(dr["attenTime"].ToString()))
                    {
                        //dr[4] ="1"+ drybCrossingRoad[i]["offTime"].ToString();
                        dr["realityTime"] = Convert.ToDateTime(de.Key).AddDays(1).ToString("yyyy-MM-dd") + " " + dr["offTime"].ToString();
                    }
                    else
                    {
                        dr["realityTime"] = de.Key.ToString() + " " + dr["offTime"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(dr["offTime"].ToString() + " " + dr["attenTime"].ToString());
                }
            }
            DataRow[] drybCrossingRoad = dtCrossingRoad.Select("grp_id=5 and zby=3", "realityTime asc");
            //int i = 0;
            for (int i = 0; i < drybCrossingRoad.Length; i++)
            {
                drybCrossingRoad[i]["offSeq"] = i + 1;
            }
        }

        /// <summary>
        /// 设置开始日期的结束时间
        /// </summary>
        public void SetEndDate()
        {
            string date = _teamAccess.GetLastDate();
            if (string.IsNullOrEmpty(date))
            {
                EndDate = DateTime.Now.ToShortDateString();
            }
            else
            {
                EndDate = Convert.ToDateTime(date).AddDays(1).ToString();
            }
        }

        #region 调班
        public List<Driver> InitDriverComboBox()
        {
            List<Driver> lstDrive = new List<Driver>();

            string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = " + line + " order by user_view_name";
            DataTable driverDT = sqlHelper.SelectDt(strSql);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();
                    driver.userid = driverDT.Rows[i]["user_id"].ToString();
                    string item = driver.userViewName + " " + driver.userName;
                    lstDrive.Add(driver);

                }
            }
            return lstDrive;

        }
        public List<Driver> InitDriverComboBox(string date)
        {
            List<Driver> lstDrive = new List<Driver>();

            string strSql = "select dcdr_userID as user_id,dcdr_userName as user_view_name  from [DriverCombineCrossingRoadPlane] where dcdr_date='" + date + "' and dcdr_cls_id<>'1' and line='" + line + "'";
            DataTable driverDT = sqlHelper.SelectDt(strSql);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    //driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();
                    driver.userid = driverDT.Rows[i]["user_id"].ToString();
                    string item = driver.userViewName + " " + driver.userName;
                    lstDrive.Add(driver);

                }
            }
            return lstDrive;

        }

        public void Replace()
        {
            MoveShift m = new MoveShift(this);
            m.ShowDialog();


        }

        /// <summary>
        /// 取消司机调班
        /// </summary>
        /// <param name="card"></param>
        public void CancelExchangeDriver(DriverCard sourceDriver)
        {
            string sid = sourceDriver.Driverid;//该位置司机的id  
            string sTempid = GetRealDriver(sourceDriver);
            string tid = "";
            string tTempid = "";
            ArrayList lstSql = new ArrayList();
            //获取临时调班的记录
            DataTable dtTemporarySwitch = GetdtSwitchedRecordByTemporary(sTempid, DateTime.Now.ToString("yyyy-MM-dd"));

            if (dtTemporarySwitch.Rows.Count > 0)
            {


                //获取第二个司机的id

                //判断与他调班的司机是否有其他调班记录
                if (dtTemporarySwitch.Rows[0]["sr_applicant"].ToString() == sTempid)
                {
                    tTempid = dtTemporarySwitch.Rows[0]["sr_changer"].ToString();
                    tid = GetUserIdFromDriverGroup(dtTemporarySwitch.Rows[0]["sr_applicant_dgid"].ToString());
                }
                else
                {
                    tTempid = dtTemporarySwitch.Rows[0]["sr_applicant"].ToString();
                    tid = GetUserIdFromDriverGroup(dtTemporarySwitch.Rows[0]["sr_changer_dgid"].ToString());
                }
                DataTable dtReplaceTemporarySwitch = GetdtSwitchedRecordByTemporary(tTempid, DateTime.Now.ToString("yyyy-MM-dd"));
                if (dtTemporarySwitch.Rows[0][0].ToString() == dtReplaceTemporarySwitch.Rows[0][0].ToString())
                {
                    //回滚调班记录

                    CancelExchangeDriverNew(sTempid, DateTime.Now.ToString("yyyy-MM-dd"));
                    //删除调班记录
                    //     string delSwitch = "delete from SwitchedRecord where ID in (" + dtTemporarySwitch.Rows[0][0].ToString() + ") or parents='" + dtTemporarySwitch.Rows[0][0].ToString() + "'";
                    //     lstSql.Add(delSwitch);
                    //     //回滚出勤时间
                    //     string updatePlanTimeSql = "update drivergroup set attentime='" + dtTemporarySwitch.Rows[0]["sr_plantime"].ToString() +
                    //"' where  id=" + dtTemporarySwitch.Rows[0]["sr_applicant_dgid"].ToString() + ";";
                    //     updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set attentime='" + dtTemporarySwitch.Rows[0]["tg_plantime"].ToString() +
                    //         "' where  id=" + dtTemporarySwitch.Rows[0]["sr_changer_dgid"].ToString();
                    //     lstSql.Add(updatePlanTimeSql);


                    //     //回滚DriverGroup的代班司机

                    //     updatePlanTimeSql = "update drivergroup set replaceDriver='" + dtTemporarySwitch.Rows[0]["sr_applicant"].ToString() + "' where ID='" + dtTemporarySwitch.Rows[0]["sr_applicant_dgid"].ToString() + "' ;";
                    //     updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set replaceDriver='" + dtTemporarySwitch.Rows[0]["sr_changer"].ToString() + "' where ID='" + dtTemporarySwitch.Rows[0]["sr_changer_dgid"].ToString() + "' ;";

                    //     updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set replaceDriver=null where replaceDriver=dgrp_user_id ;";

                    //     //回滚报表的代班司机数据

                    //     lstSql.Add(updatePlanTimeSql);

                    //回滚报表的代班司机
                    /*  lstSql.Add(setNexDayReplaceDriverByCrsPlane(sid, tTempid, DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")));
                      lstSql.Add(setNexDayReplaceDriverByCrsPlane(tid, sTempid, DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")));

                      //如果是晚班 那么回滚早班的
                      if (sourceDriver.Driver_group == "3")
                      {
                          lstSql.Add(setNexDayReplaceDriverByCrsPlane(sid, tTempid, DateTime.Now.ToString("yyyy-MM-dd")));
                          lstSql.Add(setNexDayReplaceDriverByCrsPlane(tid, sTempid, DateTime.Now.ToString("yyyy-MM-dd")));
                      }*/


                    // sqlHelper.ExecuteSqlTran(lstSql);



                }
                else
                {

                    MessageBox.Show("司机已再次调班 无法取消调班记录！");
                    return;

                }


            }
            else
            {
                MessageBox.Show(sourceDriver.DriverName + "没有临时调班记录！");
                return;
            }




            //刷新界面
            InitCardsCollections();
        }


        public void CancelExchangeDriver1(DriverCard card)
        {
            //查找对应 司机
            DataTable dtSourceSwitch = GetdtSwitchedRecord(card.Driverid, DateTime.Now.ToString("yyyy-MM-dd"));
            string sourCardId = card.Driverid;
            string targetCardId = "";

            if (dtSourceSwitch.Rows.Count > 0)
            {
                if (dtSourceSwitch.Rows[0]["sr_applicant"].ToString() == sourCardId)
                {
                    targetCardId = dtSourceSwitch.Rows[0]["sr_changer"].ToString();
                }
                else
                {
                    targetCardId = dtSourceSwitch.Rows[0]["sr_applicant"].ToString();
                }
            }
            else
            {
                return;
            }

            //再判断最后调班的对象
            DataTable dttarget = GetdtSwitchedRecord(targetCardId, DateTime.Now.ToString("yyyy-MM-dd"));

            if (dttarget.Rows[0][0].ToString() != dtSourceSwitch.Rows[0][0].ToString())
            {
                MessageBox.Show("司机已再次调班 无法取消调班记录！");
                return;
            }
            string updatePlanTimeSql = "update drivergroup set attentime='" + dtSourceSwitch.Rows[0]["sr_plantime"].ToString() +
                "' where  id=" + dtSourceSwitch.Rows[0]["sr_applicant_dgid"].ToString() + ";";
            updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set attentime='" + dtSourceSwitch.Rows[0]["tg_plantime"].ToString() +
                "' where  id=" + dtSourceSwitch.Rows[0]["sr_changer_dgid"].ToString();
            sqlHelper.ExecuteSql(updatePlanTimeSql);
            //string sr_appliceID = "select * from drivergroup where  id=" + dtSourceSwitch.Rows[0]["sr_applicant_dgid"].ToString() + ";";
            //string sr_changeID = "select * from drivergroup where id=" + dtSourceSwitch.Rows[0]["sr_changer_dgid"].ToString();

            //DataTable dtChangeId = sqlHelper.SelectDt(sr_appliceID);
            //DataTable dtAppliceID = sqlHelper.SelectDt(sr_changeID);
            if (IsBackMove(sourCardId, targetCardId, false, false) == false)
            {
                return;
            }
            else
            {


                //,attentime='" + dtSourceSwitch.Rows[0]["sr_plantime"].ToString()+ "
                //,attentime='" + dttarget.Rows[0]["sr_plantime"].ToString() + "

                //string sqlBack = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sourCardId + "' or dgrp_user_id='" + targetCardId + "';";
                ////查找出这两个司机对应的调班记录
                //dtSourceSwitch = GetdtSwitchedRecord(sourCardId, DateTime.Now.ToString("yyyy-MM-dd"));




                updatePlanTimeSql = "update drivergroup set replaceDriver='" + dtSourceSwitch.Rows[0]["sr_applicant"].ToString() + "' where ID='" + dtSourceSwitch.Rows[0]["sr_applicant_dgid"].ToString() + "' ;";
                updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set replaceDriver='" + dtSourceSwitch.Rows[0]["sr_changer"].ToString() + "' where ID='" + dtSourceSwitch.Rows[0]["sr_changer_dgid"].ToString() + "' ;";

                updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set replaceDriver=null where replaceDriver=dgrp_user_id ;";
                sqlHelper.ExecuteSql(updatePlanTimeSql);

                //if (dtSourceSwitch.Rows.Count > 0)
                //{
                //    if (Convert.ToDateTime(dtSourceSwitch.Rows[0]["sr_appdate"].ToString()).ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                //    {
                //        sqlBack = sqlBack + "update DriverGroup set replaceDriver='" + dtSourceSwitch.Rows[0]["sr_changer"].ToString() + "' where dgrp_user_id='" + dtSourceSwitch.Rows[0]["sr_applicant"].ToString() + "';";
                //    }

                //    if (!string.IsNullOrEmpty(dtSourceSwitch.Rows[0]["sr_chgdate"].ToString()))
                //    {
                //        if (Convert.ToDateTime(dtSourceSwitch.Rows[0]["sr_chgdate"].ToString()).ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                //        {
                //            sqlBack = sqlBack + "update DriverGroup set replaceDriver='" + dtSourceSwitch.Rows[0]["sr_applicant"].ToString() + "' where dgrp_user_id='" + dtSourceSwitch.Rows[0]["sr_changer"].ToString() + "';";
                //        }
                //    }
                //}
                //dttarget = GetdtSwitchedRecord(targetCardId, DateTime.Now.ToString("yyyy-MM-dd"));

                //if (dttarget.Rows.Count > 0)
                //{

                //    if (Convert.ToDateTime(dttarget.Rows[0]["sr_appdate"].ToString()).ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                //    {
                //        sqlBack = sqlBack + "update DriverGroup set replaceDriver='" + dttarget.Rows[0]["sr_changer"].ToString() + "' where dgrp_user_id='" + dttarget.Rows[0]["sr_applicant"].ToString() + "';";
                //    }

                //    if (!string.IsNullOrEmpty(dttarget.Rows[0]["sr_chgdate"].ToString()))
                //    {
                //        if (Convert.ToDateTime(dttarget.Rows[0]["sr_chgdate"].ToString()).ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                //        {
                //            sqlBack = sqlBack + "update DriverGroup set replaceDriver='" + dttarget.Rows[0]["sr_applicant"].ToString() + "' where dgrp_user_id='" + dttarget.Rows[0]["sr_changer"].ToString() + "';";
                //        }
                //    }
                //}
                //sqlHelper.ExecuteSql(sqlBack);
            }
            InitCardsCollections();
        }



        public bool CancelExchangeDriver(string souceId, string date)
        {
            //查找对应 司机
            DataTable dtSourceSwitch = GetdtSwitchedRecord(souceId, date);
            string sourCardId = souceId;
            string targetCardId = "";
            string targetDate = "";
            string souceDate = "";
            if (dtSourceSwitch.Rows.Count > 0)
            {
                if (dtSourceSwitch.Rows[0]["sr_appleader"].ToString() == sourCardId)
                {
                    targetCardId = dtSourceSwitch.Rows[0]["sr_changer"].ToString();
                    targetDate = dtSourceSwitch.Rows[0]["sr_chgdate"].ToString();
                    souceDate = dtSourceSwitch.Rows[0]["sr_appdate"].ToString();
                }
                else
                {
                    targetCardId = dtSourceSwitch.Rows[0]["sr_applicant"].ToString();
                    targetDate = dtSourceSwitch.Rows[0]["sr_appdate"].ToString();
                    souceDate = dtSourceSwitch.Rows[0]["sr_chgdate"].ToString();
                }
            }
            else
            {
                return false;
            }

            if (IsBackMove(sourCardId, targetCardId, souceDate, targetDate, false) == true)
            {
                return true;
            }
            return false;

        }
        private void UpdatePlanTime(string sourceAttTime, string targetAttTime, string sourcePlanTime, string targetPlanTime, string sourceDgId, string targetDgId)
        {
            ArrayList list = new ArrayList();
            if (sourceAttTime == null)
            {
                string sqlFormat = "update drivergroup set attenTime='{0}' where id={1}";
                if (targetPlanTime != null)
                {
                    string sql1 = string.Format(sqlFormat, targetPlanTime, sourceDgId);
                    list.Add(sql1);
                }
                string sql = string.Format(sqlFormat, sourcePlanTime, targetDgId);


                list.Add(sql);

            }
            else
            {
                string sqlFormat = "update drivergroup set dgrp_attendtime='{0}',attenTime='{1}' where id={2}";
                string sql = string.Format(sqlFormat, sourceAttTime, sourcePlanTime, targetDgId);
                string sql1 = string.Format(sqlFormat, targetAttTime, targetPlanTime, sourceDgId);
                list.Add(sql);
                list.Add(sql1);
            }

            sqlHelper.ExecuteSqlTran(list);
        }
        private void RestoreAttendTime(string sourceId, string targetId)
        {
            string date = DateTime.Now.ToString("yyyy-MM-dd");

        }
        private bool ExchangeAttendTime(DriverCard sourceDriver, DriverCard targetDriver, ref string srpt, ref string tgpt
            )
        {
          /*  string date = DateTime.Now.ToString("yyyy-MM-dd");
            int sourceType = _teamAccess.GetDriverGrpType(sourceDriver.Driverid, date, line.ToString());
            int targetType = _teamAccess.GetDriverGrpType(targetDriver.Driverid, date, line.ToString());
            //非正线司机不能临时调班
            if (sourceType != 5)
            {
                return true;
            }

            //获取司机出勤情况
            DataTable dtSourceDriver = _teamAccess.GetDutyDriver(sourceDriver.DriverGroupId.ToString());
            DataTable dtTargetDriver = _teamAccess.GetDutyDriver(targetDriver.DriverGroupId.ToString());
            if (dtSourceDriver.Rows.Count > 0 && dtTargetDriver.Rows.Count > 0)
            {
                srpt = dtSourceDriver.Rows[0]["attentime"].ToString();
                tgpt = dtTargetDriver.Rows[0]["attentime"].ToString();

                //adgid = dtSourceDriver.Rows[0]["id"].ToString();
                //cdgid = dtTargetDriver.Rows[0]["id"].ToString();
                if (dtSourceDriver.Rows[0]["dgrp_attendtime"] == DBNull.Value)
                {

                    if (targetType == 5)
                    {
                        if (dtTargetDriver.Rows[0]["dgrp_attendtime"] == DBNull.Value)
                        {
                            string sourcePlanTime = dtSourceDriver.Rows[0]["attenTime"].ToString();
                            string targetPlanTime = dtTargetDriver.Rows[0]["attenTime"].ToString();
                            string sid = dtSourceDriver.Rows[0]["id"].ToString();
                            string tid = dtTargetDriver.Rows[0]["id"].ToString();

                            UpdatePlanTime(null, null, sourcePlanTime, targetPlanTime, sid, tid);
                        }
                    }
                    else
                    {
                        if (dtTargetDriver.Rows[0]["dgrp_attendtime"] == DBNull.Value)
                        {
                            string sourcePlanTime = dtSourceDriver.Rows[0]["attenTime"].ToString();
                            string targetPlanTime = dtTargetDriver.Rows[0]["attenTime"].ToString();
                            string sid = dtSourceDriver.Rows[0]["id"].ToString();
                            string tid = dtTargetDriver.Rows[0]["id"].ToString();

                            UpdatePlanTime(null, null, sourcePlanTime, null, sid, tid);
                        }
                    }
                }
                else
                {
                    if (dtTargetDriver.Rows[0]["dgrp_attendtime"] != DBNull.Value)
                    {
                        MessageBoxHelper.ShowError("司机不满足调班条件，调班司机已经出勤");
                        return false;
                    }
                }
            }
            else
            {
                MessageBoxHelper.ShowError("找不到司机");
                return false;
            }

            //DataTable dt=_teamAccess.getd*/


            return true;
        }

        /// <summary>
        /// 新的调班逻辑
        /// </summary>
        /// <param name="sourceDriver"></param>
        /// <param name="targetDriver"></param>
        public bool ExchangeDriver(DriverCard sourceDriver, DriverCard targetDriver)
        {

            //查找两个司机真真对应的司机
            string sid = sourceDriver.Driverid;//该位置司机的id
            string tid = targetDriver.Driverid;
            string sTempid = GetRealDriver(sourceDriver);
            string tTempid = GetRealDriver(targetDriver);
            ArrayList lstSql = new ArrayList();
            //判断是不是休班与休班对话 如果是 不能进行调班
            if (sourceDriver.Driver_group == "1" && targetDriver.Driver_group == "1")
            {
                MessageBox.Show("休班与休班不能进行调班");
                return false;
            }

            //判断司机是不是同组司机 如果不是同组司机 不能进行调班
            if (sourceDriver.Driver_group == targetDriver.Driver_group)
            {
                //判断两个司机是否进行回滚操作的 如果是 那么混滚
                if (false)
                {
                    //两个司机进行混滚操作

                    //CancelExchangeDriver(sourceDriver);
                    //return;

                }
                else
                {
                    //进行正常的调班操作
                    //判断调班后两组司机是不是至少有一个是电客车司机

                    if (IsCanChangeByDriverType(sid, tid, DateTime.Now.ToString("yyyy-MM-dd")) == false)
                    {
                        //判断申请司机
                        MessageBox.Show("调班后'" + sourceDriver.DriverName + "'所在班组没有电客车司机");
                        return false;
                    }

                    if (IsCanChangeByDriverType(tid, sid, DateTime.Now.ToString("yyyy-MM-dd")) == false)
                    {
                        //判断替代司机
                        MessageBox.Show("调班后'" + targetDriver.DriverName + "'所在班组没有电客车司机");
                        return false;
                    }

                    //进行时间的调整
                    string srpt = null;
                    string tgpt = null;

                    if (!ExchangeAttendTime(sourceDriver, targetDriver, ref srpt, ref tgpt))
                    {
                        return false;
                    }
                    //更新DriverGroup 
                    string updateDriverGroup = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sid + "' or dgrp_user_id='" + tid + "'; ";
                    updateDriverGroup = updateDriverGroup + "update DriverGroup set replaceDriver='" + sTempid + "' where dgrp_user_id='" + tid + "' and dgrp_user_id<>'" + sid + "' ;";
                    updateDriverGroup = updateDriverGroup + " update DriverGroup set replaceDriver='" + tTempid + "' where dgrp_user_id='" + sid + "' and dgrp_user_id<>'" + tid + "'";
                    updateDriverGroup = updateDriverGroup + " update DriverGroup set replaceDriver=null where dgrp_user_id=replaceDriver;";

                    //updateDriverGroup = updateDriverGroup + "update DriverCombineCrossingRoadPlane set replaceDriver='" + sTempid + "' where dcdr_userID='" + tid + "' and dcdr_userID<>'" + sid + "' and dcdr_date='"+DateTime.Now.ToString("yyyy-MM-dd")+"' ;";
                    //updateDriverGroup = updateDriverGroup + " update DriverCombineCrossingRoadPlane set replaceDriver='" + tTempid + "' where dcdr_userID='" + sid + "' and dcdr_userID<>'" + tid + "' and dcdr_date='" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
                    //updateDriverGroup = updateDriverGroup + " update DriverCombineCrossingRoadPlane set replaceDriver=null where dcdr_userID=replaceDriver;";


                    lstSql.Add(updateDriverGroup);
                    //查找今天对应的班次
                    lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sid, sTempid, tid, tTempid, DateTime.Now.ToString("yyyy-MM-dd"), "0"));

                    //获取更改班次的id

                    DataTable dts = GetCrsInfoByUseId(sid, DateTime.Now.ToString("yyyy-MM-dd"));
                    DataTable dtt = GetCrsInfoByUseId(tid, DateTime.Now.ToString("yyyy-MM-dd"));

                    //插入一条调班记录
                    SwitchedRecord swr = new SwitchedRecord();
                    swr.sr_applicant = sTempid;
                    swr.sr_SouceApplicant = sid;
                    swr.sr_changer = tTempid;
                    swr.sr_SouceChanger = tid;
                    swr.sr_reason = "临时调班";
                    swr.sr_appdate = DateTime.Now.ToString("yyyy-MM-dd");
                    swr.sr_appnum = GetCrossingRoad(sourceDriver.Driver_group, sourceDriver.CrossNum);
                    swr.sr_chgdate = DateTime.Now.ToString("yyyy-MM-dd");
                    swr.sr_chgnum = GetCrossingRoad(targetDriver.Driver_group, targetDriver.CrossNum); ;
                    swr.sr_appleader = "";
                    swr.sr_appresult = "";
                    swr.st_apppby = CONSTDATA.UserModel.ID;
                    swr.st_apppbyresult = "";
                    swr.sr_chgleader = "";
                    swr.sr_chgleaderresult = "";
                    swr.sr_chgpby = "";
                    swr.sr_chgpbyresult = "";
                    swr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
                    swr.parents = "";
                    swr.sr_plantime = srpt;
                    swr.tg_plantime = tgpt;
                    swr.is_tmp_exchange = "1";
                    swr.sr_applicant_dgid = sourceDriver.DriverGroupId.ToString();
                    swr.sr_changer_dgid = targetDriver.DriverGroupId.ToString();
                    swr.applyDayAppMonthID = dts.Rows[0][0].ToString();
                    swr.backToDayBackMonthID = dtt.Rows[0][0].ToString();
                    string insertSwitchedRecord = SetSwitchedRecord(swr);
                    object obj = sqlHelper.GetSingle(insertSwitchedRecord);
                    if (sourceDriver.Driver_group == "3" || targetDriver.Driver_group == "3")
                    {
                        //设置早班

                        string sNextCrsNum = GetNextDayCrsNum(sid, DateTime.Now.ToString("yyyy-MM-dd"));
                        string tNextCrsNum = GetNextDayCrsNum(tid, DateTime.Now.ToString("yyyy-MM-dd"));
                        if (string.IsNullOrEmpty(sNextCrsNum))
                        {
                            MessageBox.Show(sourceDriver.DriverName + "所在组 明天没有排班记录");
                            delSwitchedRecord(Convert.ToString(obj));
                            return false;
                        }
                        if (string.IsNullOrEmpty(tNextCrsNum))
                        {
                            MessageBox.Show(sourceDriver.DriverName + "所在组 明天没有排班记录");
                            delSwitchedRecord(Convert.ToString(obj));
                            return false;
                        }
                        dts = GetCrsInfoByUseId(sid, DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
                        dtt = GetCrsInfoByUseId(tid, DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
                        //设置第报表的调班人员
                        swr.sr_appnum = sNextCrsNum;
                        swr.sr_chgnum = tNextCrsNum;
                        swr.sr_appdate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_chgdate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                        swr.applyDayAppMonthID = dts.Rows[0][0].ToString();
                        swr.backToDayBackMonthID = dtt.Rows[0][0].ToString();
                        swr.parents = Convert.ToString(obj);
                        //早班的调班记录
                        insertSwitchedRecord = SetSwitchedRecord(swr);
                        lstSql.Add(insertSwitchedRecord);
                        // string updateCrsPlane=setNexDayReplaceDriverByCrsPlane(sid, tTempid,DateTime.Now.ToString("yyyy-MM-dd"));
                        lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sid, sTempid, tid, tTempid, DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"), "0"));
                        // updateCrsPlane = setNexDayReplaceDriverByCrsPlane(tid, sTempid, DateTime.Now.ToString("yyyy-MM-dd"));
                        // lstSql.Add(updateCrsPlane);

                    }
                    try
                    {
                        sqlHelper.ExecuteSqlTran(lstSql);

                    }
                    catch (Exception ex)
                    {
                        delSwitchedRecord(Convert.ToString(obj));
                        MessageBox.Show("调班失败！" + ex.ToString());
                        Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
                        return false;
                    }


                }

                //判断换班后司机组中是否有电客车司机           
                //不是 进行正常调班
                //插入一条正常的调班记录
                //更新driverGroup
            }
            else
            {
                MessageBox.Show("不同组司机不能进行临时调班");
            }

            //刷新界面
            InitCardsCollections();
            return true;

        }

        //public void ExchangeDriver1(DriverCard sourceDriver, DriverCard targetDriver)
        //{

        //    ////添加调班验证

        //    ////判断申请人是不是早班 如果是早班 不给申请

        //    ////申请那天司机的班次
        //    //string appDateSourceDrive = DriverClsType(sourceDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd"));
        //    ////申请当天 替班司机的 班次
        //    //string appDateChangeDrive = DriverClsType(targetDriver.Driverid.ToString(), DateTime.Now.ToString("yyyy-MM-dd"));


        //    //if (appDateSourceDrive == "0")
        //    //{
        //    //    MessageBox.Show("早班司机不能申请调班");
        //    //    return;
        //    //}
        //    //if (appDateSourceDrive == "1")
        //    //{
        //    //    MessageBox.Show("休班司机不能申请调班");
        //    //    return;
        //    //}
        //    //if (appDateSourceDrive == "2")
        //    //{
        //    //    if (appDateChangeDrive != "1")
        //    //    {
        //    //        if (appDateChangeDrive != "2")
        //    //        {
        //    //            MessageBox.Show("白班只能与休班司机换班");
        //    //            return;
        //    //        }
        //    //    }
        //    //}
        //    //if (appDateSourceDrive == "3")
        //    //{
        //    //    if (appDateChangeDrive != "0")
        //    //    {
        //    //        if (appDateChangeDrive != "3")
        //    //        {
        //    //            MessageBox.Show("晚班只能与早班司机换班");
        //    //            return;
        //    //        }
        //    //    }
        //    //}

        //    MessageBoxResult dr = MessageBoxResult.Yes;
        //    if (dr == MessageBoxResult.Yes)
        //    {
        //        if (IsCanChangeByDriverType(sourceDriver.Driverid, targetDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd"))==false)
        //        {
        //            MessageBox.Show("调班后司机组不存在正式电客车司机");
        //            return;
        //        }
        //        if (IsCanChangeByDriverType(targetDriver.Driverid, sourceDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd")) == false)
        //        {
        //            MessageBox.Show("还班时司机组不存在正式电客车司机");
        //            return;
        //        }
        //    }
        //    else
        //    {
        //        if (IsCanChangeByDriverType(sourceDriver.Driverid, targetDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd")) == false)
        //        {
        //            MessageBox.Show("调班后司机组不存在正式电客车司机");
        //            return;
        //        }

        //    }
        //    string sid, tid;
        //    if (string.IsNullOrEmpty(sourceDriver.ReplaceDriverId))
        //        sid = sourceDriver.Driverid;
        //    else
        //        sid = sourceDriver.ReplaceDriverId;

        //    if (string.IsNullOrEmpty(targetDriver.ReplaceDriverId))
        //        tid = targetDriver.Driverid;
        //    else
        //        tid = targetDriver.ReplaceDriverId;

        //    string srpt=null;
        //    string tgpt=null;
        //    if (!ExchangeAttendTime(sourceDriver, targetDriver,ref srpt,ref tgpt))
        //    {
        //        return;
        //    }
        //    //判断是不是回滚
        //    if (IsBackMoveBySameRecord(sourceDriver.Driverid, targetDriver.Driverid))
        //    {

        //        string sqlBack = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sourceDriver.Driverid + "' or dgrp_user_id='" + targetDriver.Driverid + "';";
        //        sqlHelper.ExecuteSql(sqlBack);
        //    }

        //    else
        //    {
        //      /*  if (IsBackMove(sourceDriver.Driverid, targetDriver.Driverid) == false)
        //        {
        //            return;
        //        }
        //        else
        //        {
        //            string sqlBack = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sourceDriver.Driverid + "' or dgrp_user_id='" + targetDriver.Driverid + "';";
        //            sqlHelper.ExecuteSql(sqlBack);
        //        }*/

        //        // if(sourceDriver)
        //        //判断

        //        if (dr == MessageBoxResult.Yes)
        //        {


        //            string souceidTemp = "";
        //            string targetidTemp = "";
        //            if (string.IsNullOrEmpty(sourceDriver.ReplaceDriverId))
        //            {
        //                souceidTemp = sourceDriver.Driverid;
        //            }
        //            else
        //            {
        //                souceidTemp = sourceDriver.ReplaceDriverId;
        //            }

        //            if (string.IsNullOrEmpty(targetDriver.ReplaceDriverId))
        //            {
        //                targetidTemp = targetDriver.Driverid;
        //            }
        //            else
        //            {
        //                targetidTemp = targetDriver.ReplaceDriverId;
        //            }

        //           // exchangeMonthsClassBySameDay(souceidTemp, targetidTemp, DateTime.Now.ToString("yyyy-MM-dd"));
        //            //更改Driver的replaceDriver
        //            string updateDriverGroup = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sourceDriver.Driverid + "' or dgrp_user_id='" + targetDriver.Driverid + "'; update DriverGroup set replaceDriver='" + souceidTemp + "' where dgrp_user_id='" + targetDriver.Driverid + "' and dgrp_user_id<>'" + sourceDriver.Driverid + "' ; update DriverGroup set replaceDriver='" + targetidTemp + "' where dgrp_user_id='" + sourceDriver.Driverid + "' and dgrp_user_id<>'" + targetDriver.Driverid + "'";

        //            sqlHelper.ExecuteSql(updateDriverGroup);
        //            ////////////////////////////////////////////////////////////////////////
        //            //判断是否已经出勤 A和B都未出勤 那么计划出勤时间改为热备

        //            //其他 计划出勤时间互换 实际出勤时间互换

        //            ////////////////////////////////////////////////////////////////////////



        //            //加入一条调班记录
        //            string sourceReMark = "";
        //            string targeReMark = "";
        //            //查找原先对应的交路
        //            //string sourceSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver.Driverid + "'";
        //            //DataTable dtSource = sqlHelper.SelectDt(sourceSql);
        //            //if (dtSource.Rows.Count > 0)
        //            //{
        //            //    sourceReMark = dtSource.Rows[0][0].ToString();
        //            //}
        //            sourceReMark = GetCrossRemark(DateTime.Now.ToString("yyyy-MM-dd"), sourceDriver.Driverid);
        //            string sqlInsetr = "";

        //            //string targetSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and dcdr_userID='" + targetDriver.Driverid + "'";
        //            //DataTable dttargetSql = sqlHelper.SelectDt(targetSql);
        //            //if (dttargetSql.Rows.Count > 0)
        //            //{
        //            //    targeReMark = dttargetSql.Rows[0][0].ToString();
        //            //}



        //            targeReMark = GetCrossRemark(DateTime.Now.ToString("yyyy-MM-dd"), targetDriver.Driverid);

        //            string today = DateTime.Now.ToString("yyyy-MM-dd");
        //            SwitchedRecord sr = new SwitchedRecord();
        //            sr.sr_applicant = souceidTemp;
        //            sr.sr_changer = targetidTemp;
        //            sr.sr_appdate = today;
        //            sr.sr_chgdate = today;

        //            sr.st_apppby = CONSTDATA.UserModel.ID;
        //            sr.sr_approvaldate = today;
        //            sr.sr_appresult = "1";
        //            sr.st_apppbyresult = "1";
        //            sr.sr_chgpbyresult = "1";
        //            sr.sr_chgleaderresult = "1";
        //            sr.sr_appnum = sourceReMark;
        //            sr.sr_chgnum = targeReMark;
        //            sr.sr_reason = "临时调班";
        //            sr.sr_applicant_dgid = sourceDriver.DriverGroupId.ToString();
        //            sr.sr_changer_dgid = targetDriver.DriverGroupId.ToString();

        //          //  sqlInsetr = "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate, sr_chgdate,st_apppby,sr_approvaldate,sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum," +
        //          //      "sr_chgnum,sr_reason,sr_plantime,tg_plantime,sr_applicant_dgid,sr_changer_dgid) values('" + souceidTemp + "','"
        //          //+ targetidTemp + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" +
        //          //Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + sourceReMark + "','" +
        //          //targeReMark + "','" + "临时调班" + "','" + srpt + "','" + tgpt + "'," + appliDgid + "," + changerDgid + ");select @@IDENTITY";
        //            object obj = sqlHelper.GetSingle(SetSwitchedRecord(sr));

        //            //setNexDayByZB(sourceDriver.Driverid, targetDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd"), "临时调班", Convert.ToString(obj),false);
        //            //setNexDayByZB(targetDriver.Driverid, sourceDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd"), "临时调班", Convert.ToString(obj),false);
        //            setNexDayByZB(sourceDriver, targetDriver, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"), "临时调班", Convert.ToString(obj), false);
        //        }
        //        else 
        //        {

        //            //下面的代码暂时不能用，切记
        //           string sourceReMark = GetCrossRemark(DateTime.Now.ToString("yyyy-MM-dd"), sourceDriver.Driverid);
        //           string  sqlInsetr = "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate, st_apppby,sr_approvaldate,sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum,sr_reason) values('" + sourceDriver.Driverid + "','"
        //     + targetDriver.Driverid + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + sourceReMark + "','临时调班');select @@IDENTITY";


        //            object obj=sqlHelper.GetSingle(sqlInsetr);

        //            string updateDriverGroup = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sourceDriver.Driverid + "' or dgrp_user_id='" + targetDriver.Driverid + "';  update DriverGroup set replaceDriver='" + targetDriver.Driverid + "' where dgrp_user_id='" + sourceDriver.Driverid + "' and dgrp_user_id<>'" + targetDriver.Driverid + "'";
        //            sqlHelper.ExecuteSql(updateDriverGroup);

        //            //不需要还班
        //            exchangeMonthsClass(sourceDriver.Driverid, targetDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd"), "1");
        //            setNexDayByZB(sourceDriver.Driverid, targetDriver.Driverid, DateTime.Now.ToString("yyyy-MM-dd"), "临时调班", Convert.ToString(obj), sourceDriver.DriverGroupId.ToString(), targetDriver.DriverGroupId.ToString());
        //        }
        //    }

        //    //刷新主页面
        //    InitCardsCollections();
        //}
        public bool IsCanChangeByDriverTypeBySameDay(string sourceDriver, string tagerDriver, string date, string tranId)
        {
            return IsCanChangeByDriverType(sourceDriver, tagerDriver, date, tranId);
            //判断是不是月备班 如果月备班返回true
            //string sql = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + sourceDriver + "' and dcdr_date='" + date + "' and dcdr_driverType='6'";
            //DataTable dtybb = sqlHelper.SelectDt(sql, tranId);

            //string sql1 = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + tagerDriver + "' and dcdr_date='" + date + "' and dcdr_driverType='6'";
            //DataTable dtybb1 = sqlHelper.SelectDt(sql1, tranId);
            //if (dtybb.Rows.Count > 0 || dtybb1.Rows.Count>0)
            //{
            //    return true;
            //}
            //string str = "select * from [System_User] where  [user_id] in ( select case when replaceDriver is null then dcdr_userID  else replaceDriver  end  as userid  from DriverCombineCrossingRoadPlane where( dcdr_driverCombineId in ( select dcdr_driverCombineId  from DriverCombineCrossingRoadPlane where dcdr_userID='" + sourceDriver + "' and dcdr_date='" + date + "' ) and dcdr_userID<>'" + sourceDriver + "')  or dcdr_userID='" + tagerDriver + "' and dcdr_date='" + date + "' ) and user_post =15";
            //DataTable dt = sqlHelper.SelectDt(str, tranId);
            //if (dt.Rows.Count > 0)
            //{
            //    return true;
            //}

            //return false;

        }

        public bool IsCanChangeByDriverType(string sourceDriver, string tagerDriver, string date, string tranId)
        {
            //判断是不是月备班 如果月备班返回true
            string sql = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + sourceDriver + "' and dcdr_date='" + date + "' and dcdr_driverType='6'";
            DataTable dtybb = sqlHelper.SelectDt(sql, tranId);
            if (dtybb.Rows.Count > 0)
            {
                return true;
            }
            string str = "select * from [System_User] where  [user_id] in ( select case when replaceDriver is null then dcdr_userID  else replaceDriver  end  as userid  from DriverCombineCrossingRoadPlane where( dcdr_driverCombineId in ( select dcdr_driverCombineId  from DriverCombineCrossingRoadPlane where dcdr_userID='" + sourceDriver + "' and dcdr_date='" + date + "' ) and dcdr_userID<>'" + sourceDriver + "')  or dcdr_userID='" + tagerDriver + "' and dcdr_date='" + date + "' ) and user_post =15";
            DataTable dt = sqlHelper.SelectDt(str, tranId);
            if (dt.Rows.Count > 0)
            {
                return true;
            }

            return false;

        }
        public bool IsCanChangeByDriverType(string sourceDriver, string tagerDriver, string date)
        {
            //判断是不是月备班 如果月备班返回true
            string sql = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + sourceDriver + "' and dcdr_date='" + date + "' and dcdr_driverType='6'";
            DataTable dtybb = sqlHelper.SelectDt(sql);
            if (dtybb.Rows.Count > 0)
            {
                return true;
            }
            string str = "select * from [System_User] where  [user_id] in ( select case when replaceDriver is null then dcdr_userID  else replaceDriver  end  as userid  from DriverCombineCrossingRoadPlane where( dcdr_driverCombineId in ( select dcdr_driverCombineId  from DriverCombineCrossingRoadPlane where dcdr_userID='" + sourceDriver + "' and dcdr_date='" + date + "' ) and dcdr_userID<>'" + sourceDriver + "')  or dcdr_userID='" + tagerDriver + "' and dcdr_date='" + date + "' ) and user_post =15";
            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                return true;
            }

            return false;

        }

        /// <summary>
        ///修改还班的信息
        /// </summary>
        public bool setBackClsInfo(string appSBackPlane, string appTBackPlane, string targetDate, string cmbsouceDrive, string cmbtagerDriver, ArrayList lstSql, string id)
        {

            DataTable sBackdtPlane = GetCrsInfoById(appSBackPlane);

            DataTable tBackdtPlane = GetCrsInfoById(appTBackPlane);

            //还班那天的信息

            string sourcebackDriver = "";
            string targetbackDriver = "";
            string sourcebackReplaceDriver = "";
            string targetbackReplaceDriver = "";

            GetDriverInToPlane(sBackdtPlane, ref sourcebackDriver, ref sourcebackReplaceDriver);
            GetDriverInToPlane(tBackdtPlane, ref targetbackDriver, ref targetbackReplaceDriver);

            if (cmbtagerDriver == targetbackDriver)
            {
                sourcebackReplaceDriver = sourcebackDriver;
            }

            //ArrayList lstSql = new ArrayList(); 

            //设置还班当天的信息
            lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetbackDriver, targetbackReplaceDriver, sourcebackDriver, sourcebackReplaceDriver, targetDate, "1"));
            //更改还班时间

            string strUpdateSwr = "update SwitchedRecord set sr_chgdate='" + targetDate + "' where ID='" + id + "'";
            lstSql.Add(strUpdateSwr);

            //判断是不是今天的 如果是今天的 更改DriverGroup

            if (targetDate == DateTime.Now.ToString("yyyy-MM-dd"))
            {

                lstSql.Add(setDriverGroupByReplace(targetbackDriver, sourcebackReplaceDriver));

            }
            //判断是否是第二天是晚班
            if (tBackdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
            {

                //还班
                //申请司机当天为晚班 需要调早班
                DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourcebackDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                //替班司机申请当天的计划信息
                DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetbackDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                if (sBackNextDaydtPlane == null)
                {
                    //  delSwitchedRecord(Convert.ToString(obj));
                    MessageBox.Show("调班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                    return false;
                }
                if (tBackNextDaydtPlane == null)
                {
                    // delSwitchedRecord(Convert.ToString(obj));
                    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                    return false;
                }
                if (IsCanChangeByDriverType(targetbackDriver, sourcebackDriver, targetDate) == false)
                {
                    // delSwitchedRecord(Convert.ToString(obj));
                    MessageBox.Show("调班后替班司机组" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                    return false;
                }
                lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetbackDriver, targetbackReplaceDriver, sourcebackDriver, sourcebackReplaceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                //插入新的调班记录

                SwitchedRecord swr = new SwitchedRecord();
                swr.sr_applicant = sourcebackReplaceDriver;
                swr.sr_SouceApplicant = sourcebackDriver;
                swr.sr_changer = targetbackReplaceDriver;
                swr.sr_SouceChanger = targetbackDriver;
                // swr.sr_reason = reson;
                swr.sr_appdate = Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd");
                swr.sr_appnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                swr.sr_chgdate = "";
                swr.sr_chgnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                swr.sr_appleader = "";
                swr.sr_appresult = "";
                swr.st_apppby = CONSTDATA.UserModel.ID;
                swr.st_apppbyresult = "";
                swr.sr_chgleader = "";
                swr.sr_chgleaderresult = "";
                swr.sr_chgpby = "";
                swr.sr_chgpbyresult = "";
                swr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
                swr.parents = id;
                swr.sr_plantime = "";
                swr.tg_plantime = "";
                swr.is_tmp_exchange = "0";
                swr.sr_applicant_dgid = "";
                swr.sr_changer_dgid = "";
                swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0]["ID"].ToString();
                swr.backToDayBackMonthID = tBackNextDaydtPlane.Rows[0]["ID"].ToString();
                lstSql.Add(SetSwitchedRecord(swr));

            }
            return true;

        }
        public bool ExchangeDriverNew(string appSplane, string appTplane, string appSBackPlane, string appTBackPlane, string sourceDate, string targetDate, string reson, string cmbsouceDrive, string cmbtagerDriver, string tranId)
        {
            //查找相对应的原id 和替代id

            DataTable sdtPlane = GetCrsInfoById(appSplane, tranId);

            DataTable tdtPlane = GetCrsInfoById(appTplane, tranId);
            DataTable sBackdtPlane = GetCrsInfoById(appSBackPlane, tranId);

            DataTable tBackdtPlane = GetCrsInfoById(appTBackPlane, tranId);


            string sourceDriver = "";
            string targetDriver = "";

            string sourceReplaceDriver = "";
            string targetReplaceDriver = "";
            GetDriverInToPlane(sdtPlane, ref sourceDriver, ref sourceReplaceDriver);
            GetDriverInToPlane(tdtPlane, ref targetDriver, ref targetReplaceDriver);
            if (cmbsouceDrive == sourceDriver)
            {
                targetReplaceDriver = targetDriver;
            }




            //还班那天的信息

            string sourcebackDriver = "";
            string targetbackDriver = "";
            string sourcebackReplaceDriver = "";
            string targetbackReplaceDriver = "";

            GetDriverInToPlane(sBackdtPlane, ref sourcebackDriver, ref sourcebackReplaceDriver);
            GetDriverInToPlane(tBackdtPlane, ref targetbackDriver, ref targetbackReplaceDriver);

            if (cmbtagerDriver == targetbackDriver)
            {
                sourcebackReplaceDriver = sourcebackDriver;
            }



            //申请司机申请当天的计划信息
            // DataTable sdtPlane = GetDtCrsInfo(sourceDriver, sourceDate);
            //替班司机申请当天的计划信息
            // DataTable tdtPlane = GetDtCrsInfo(targetDriver, sourceDate);

            ArrayList lstSql = new ArrayList();
            if (sdtPlane == null)
            {
                MessageBox.Show("申请司机" + sourceDate + "没有排班记录！");
                return false;
            }
            if (tdtPlane == null)
            {
                MessageBox.Show("替班司机" + sourceDate + "没有排班记录！");
                return false;
            }
            //判断司机今天是否已经存在调班记录 如果存在 先要求删除
            //DataTable dtSSwitch = GetdtSwitchedRecordByPlane(sourceDriver, sourceDate);
            //if (dtSSwitch.Rows.Count > 0)
            //{
            //    MessageBox.Show("申请司机今天已经存在调班记录，请先取消调班");
            //    return;
            //}
            //DataTable dtTSwitch = GetdtSwitchedRecordByPlane(targetDriver, sourceDate);
            //if (dtSSwitch.Rows.Count > 0)
            //{
            //    MessageBox.Show("替班司机今天已经存在调班记录，请先取消调班");
            //    return;
            //}

            if (!string.IsNullOrEmpty(targetDate))
            {
                ////需要还班
                //DataTable sBackdtPlane = GetDtCrsInfo(sourceDriver, targetDate);
                ////替班司机申请当天的计划信息
                //DataTable tBackdtPlane = GetDtCrsInfo(targetDriver, targetDate);

                if (sBackdtPlane.Rows.Count == 0)
                {
                    MessageBox.Show("申请司机" + targetDriver + "没有排班记录！");
                }
                if (tBackdtPlane.Rows.Count == 0)
                {
                    MessageBox.Show("替班司机" + targetDriver + "没有排班记录！");
                    return false;
                }
                SwitchedRecord swr = new SwitchedRecord();
                swr.sr_applicant = sourceReplaceDriver;
                swr.sr_SouceApplicant = sourceDriver;
                swr.sr_changer = targetReplaceDriver;
                swr.sr_SouceChanger = targetDriver;
                swr.sr_reason = reson;
                swr.sr_appdate = sourceDate;
                swr.sr_appnum = sdtPlane.Rows[0]["dcdr_duty"].ToString();
                swr.sr_chgdate = targetDate;
                swr.sr_chgnum = tdtPlane.Rows[0]["dcdr_duty"].ToString(); ;
                swr.sr_appleader = "";
                swr.sr_appresult = "";
                swr.st_apppby = CONSTDATA.UserModel.ID;
                swr.st_apppbyresult = "";
                swr.sr_chgleader = "";
                swr.sr_chgleaderresult = "";
                swr.sr_chgpby = "";
                swr.sr_chgpbyresult = "";
                swr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
                swr.parents = "";
                swr.sr_plantime = "";
                swr.tg_plantime = "";
                swr.is_tmp_exchange = "0";
                swr.sr_applicant_dgid = "";
                swr.sr_changer_dgid = "";
                swr.applyDayAppMonthID = appSplane;
                swr.backToDayBackMonthID = appTBackPlane;
                //判断还班和调班是否是同一天(写入报表的方式不一样)
                if (sourceDate == targetDate)
                {
                    //插入调班记录
                    if (IsCanChangeByDriverTypeBySameDay(sourceDriver, targetDriver, sourceDate, tranId) == false)
                    {
                        MessageBox.Show("调班后申请司机组没有电客车司机");
                        return false;
                    }
                    if (IsCanChangeByDriverTypeBySameDay(targetDriver, sourceDriver, sourceDate, tranId) == false)
                    {
                        MessageBox.Show("调班后替代司机组没有电客车司机");
                        return false;
                    }


                    string insertSwitchedRecord = SetSwitchedRecord(swr);
                    object obj = sqlHelper.GetSingle(insertSwitchedRecord, tranId);
                    // lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sourceDriver, targetDriver, sourceDate));

                    lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, sourceDate, "0"));

                    if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3" && tdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {
                        DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                        //替班司机申请当天的计划信息
                        DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                        if (sBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("调班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (tBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (IsCanChangeByDriverTypeBySameDay(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId) == false)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("调班后申请司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                            return false;
                        }

                        //有排班计划进行调班
                        swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_appnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0][0].ToString(); ;
                        swr.backToDayBackMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                        swr.parents = Convert.ToString(obj);
                        lstSql.Add(SetSwitchedRecord(swr));

                        //    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                        lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));

                    }
                    else
                        //判断两个班次是否有晚班的
                        if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                        {
                            //DataTable dtSSwitchNextDay = GetdtSwitchedRecordByPlane(sourceDriver,Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                            //if (dtSSwitch.Rows.Count > 0)
                            //{
                            //    MessageBox.Show("申请司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                            //    return;
                            //}
                            //DataTable dtTSwitchNextDay = GetdtSwitchedRecordByPlane(targetDriver,Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                            //if (dtSSwitch.Rows.Count > 0)
                            //{
                            //    MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                            //    return;
                            //}
                            //申请司机是晚班
                            DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                            //替班司机申请当天的计划信息
                            DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                            if (sBackNextDaydtPlane == null)
                            {
                                delSwitchedRecord(Convert.ToString(obj), tranId);
                                MessageBox.Show("调班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                return false;
                            }
                            if (tBackNextDaydtPlane == null)
                            {
                                delSwitchedRecord(Convert.ToString(obj), tranId);
                                MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                return false;
                            }
                            if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate, tranId) == false)
                            {
                                delSwitchedRecord(Convert.ToString(obj), tranId);
                                MessageBox.Show("调班后申请司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                                return false;
                            }

                            //有排班计划进行调班
                            swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                            swr.sr_appnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                            swr.sr_chgnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                            swr.sr_chgdate = "";
                            swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0][0].ToString(); ;
                            // swr.backToDayBackMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                            // swr.applyDayAppMonthID = sdtPlane.Rows[0]["dcdr_cls_id"].ToString();
                            swr.parents = Convert.ToString(obj);
                            lstSql.Add(SetSwitchedRecord(swr));

                            //    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                            lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));



                        }
                        else
                            if (tBackdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                            {
                                //DataTable dtSSwitchNextDay = GetdtSwitchedRecordByPlane(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                                //if (dtSSwitch.Rows.Count > 0)
                                //{
                                //    MessageBox.Show("申请司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                                //    return;
                                //}
                                //DataTable dtTSwitchNextDay = GetdtSwitchedRecordByPlane(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                                //if (dtSSwitch.Rows.Count > 0)
                                //{
                                //    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                                //    return;
                                //}

                                //还班
                                //申请司机当天为晚班 需要调早班
                                DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                                //替班司机申请当天的计划信息
                                DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                                if (sBackNextDaydtPlane == null)
                                {
                                    delSwitchedRecord(Convert.ToString(obj), tranId);
                                    MessageBox.Show("调班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                    return false;
                                }
                                if (tBackNextDaydtPlane == null)
                                {
                                    delSwitchedRecord(Convert.ToString(obj), tranId);
                                    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                    return false;
                                }
                                if (IsCanChangeByDriverType(targetDriver, sourceDriver, targetDate, tranId) == false)
                                {
                                    delSwitchedRecord(Convert.ToString(obj), tranId);
                                    MessageBox.Show("调班后替班司机组" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                                    return false;
                                }
                                swr.sr_appdate = Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd");
                                swr.sr_applicant = targetReplaceDriver;
                                swr.sr_changer = sourceReplaceDriver;
                                swr.sr_appnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                                swr.sr_chgnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                                swr.applyDayAppMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                                swr.sr_chgdate = "";
                                swr.parents = Convert.ToString(obj);
                                lstSql.Add(SetSwitchedRecord(swr));

                                // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "2"));
                                lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, targetReplaceDriver, sourceDriver, sourceReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));

                            }
                    try
                    {
                        if (DateTime.Now.ToString("yyyy-MM-dd") == sourceDate)
                        {
                            lstSql.Add(setDriverGroupByReplace(sourceDriver, targetDriver, targetDriver, sourceDriver));
                        }
                        sqlHelper.ExecuteSqlTran(lstSql, tranId);

                    }
                    catch
                    {
                        delSwitchedRecord(Convert.ToString(obj), tranId);
                        MessageBox.Show("调班失败！");
                        return false;
                    }


                }
                else
                {
                    if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate, tranId) == false)
                    {
                        MessageBox.Show("调班后申请司机组没有电客车司机");
                        return false;
                    }
                    if (IsCanChangeByDriverType(targetDriver, sourceDriver, targetDate, tranId) == false)
                    {
                        MessageBox.Show("调班后替代司机组没有电客车司机");
                        return false;
                    }

                    //写调班记录
                    string insertSwitchedRecord = SetSwitchedRecord(swr);
                    object obj = sqlHelper.GetSingle(insertSwitchedRecord, tranId);
                    //更改调班当天的月计划
                    // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, sourceDate, "1"));
                    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, sourceDate, "0"));
                    //更改还班当天的月计划
                    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetbackDriver, targetbackReplaceDriver, sourcebackDriver, sourcebackReplaceDriver, targetDate, "1"));
                    //lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, sourceDriver, targetDate, "2"));
                    //判断当天是不是晚班 如果是晚班的话 对白班进行调班

                    //获取当天被调班司机的班次
                    if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {

                        //申请司机当天为晚班 需要调早班
                        DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                        //替班司机申请当天的计划信息
                        DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                        if (sBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("调班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (tBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate, tranId) == false)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("调班后申请司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                            return false;
                        }
                        //生成第二天的调班计划报表信息
                        swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_appnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0][0].ToString();
                        swr.sr_chgdate = "";
                        swr.parents = Convert.ToString(obj);
                        lstSql.Add(SetSwitchedRecord(swr));
                        //lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));
                        lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));

                    }
                    //判断还班那天
                    if (tBackdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {
                        //DataTable dtSSwitchNextDay = GetdtSwitchedRecordByPlane(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //if (dtSSwitch.Rows.Count > 0)
                        //{
                        //    MessageBox.Show("申请司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                        //    return;
                        //}
                        //DataTable dtTSwitchNextDay = GetdtSwitchedRecordByPlane(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //if (dtSSwitch.Rows.Count > 0)
                        //{
                        //    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                        //    return;
                        //}
                        //还班
                        //申请司机当天为晚班 需要调早班
                        DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                        //替班司机申请当天的计划信息
                        DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                        if (sBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("调班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (tBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (IsCanChangeByDriverType(targetDriver, sourceDriver, targetDate, tranId) == false)
                        {
                            delSwitchedRecord(Convert.ToString(obj), tranId);
                            MessageBox.Show("调班后替班司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                            return false;
                        }
                        swr.sr_appdate = Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_applicant = targetReplaceDriver;
                        swr.sr_changer = sourceReplaceDriver;
                        swr.sr_appnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgdate = "";
                        swr.applyDayAppMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                        swr.parents = Convert.ToString(obj);
                        lstSql.Add(SetSwitchedRecord(swr));
                        // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "2"));
                        lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetbackDriver, targetbackReplaceDriver, sourcebackDriver, sourcebackReplaceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                    }
                    try
                    {
                        if (DateTime.Now.ToString("yyyy-MM-dd") == sourceDate)
                        {
                            lstSql.Add(setDriverGroupByReplace(sourceDriver, targetDriver));
                        }
                        if (DateTime.Now.ToString("yyyy-MM-dd") == targetDate)
                        {
                            lstSql.Add(setDriverGroupByReplace(targetDriver, sourceDriver));
                        }
                        sqlHelper.ExecuteSqlTran(lstSql, tranId);
                    }
                    catch (Exception ex)
                    {
                        delSwitchedRecord(Convert.ToString(obj), tranId);
                        MessageBox.Show("调班失败！" + ex.ToString());
                        return false;
                    }
                }



            }
            else
            {

                // ChkDriversTypeInGroup(sourceDriver,targetDriver,sourceDate)
                if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate, tranId) == false)
                {
                    MessageBox.Show("调班后申请司机组没有电客车司机");
                    return false;
                }
                //写入报表

                //  lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, sourceDate, "1"));
                lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, sourceDate, "0"));


                SwitchedRecord swr = new SwitchedRecord();
                swr.sr_applicant = sourceReplaceDriver;
                swr.sr_SouceApplicant = sourceDriver;
                swr.sr_changer = targetReplaceDriver;
                swr.sr_SouceChanger = targetDriver;
                swr.sr_reason = reson;
                swr.sr_appdate = sourceDate;
                swr.sr_appnum = sdtPlane.Rows[0]["dcdr_duty"].ToString();
                swr.sr_chgdate = "";
                swr.sr_chgnum = tdtPlane.Rows[0]["dcdr_duty"].ToString(); ;
                swr.sr_appleader = "";
                swr.sr_appresult = "";
                swr.st_apppby = CONSTDATA.UserModel.ID;
                swr.st_apppbyresult = "";
                swr.sr_chgleader = "";
                swr.sr_chgleaderresult = "";
                swr.sr_chgpby = "";
                swr.sr_chgpbyresult = "";
                swr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
                swr.parents = "";
                swr.sr_plantime = "";
                swr.tg_plantime = "";
                swr.is_tmp_exchange = "0";
                swr.sr_applicant_dgid = "";
                swr.sr_changer_dgid = "";
                swr.applyDayAppMonthID = appSplane;

                string insertSwitchedRecord = SetSwitchedRecord(swr);
                object obj = sqlHelper.GetSingle(insertSwitchedRecord, tranId);

                if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                {
                    //夜班 写第二天的调班记录
                    DataTable sNextdtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                    DataTable tNextdtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);
                    if (sNextdtPlane == null)
                    {
                        delSwitchedRecord(Convert.ToString(obj), tranId);
                        MessageBox.Show("申请司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "早班没有排班计划");
                        return false;
                    }
                    swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                    swr.sr_appnum = sNextdtPlane.Rows[0]["dcdr_duty"].ToString();
                    swr.sr_chgnum = tNextdtPlane.Rows[0]["dcdr_duty"].ToString();
                    swr.applyDayAppMonthID = sNextdtPlane.Rows[0][0].ToString();
                    swr.parents = Convert.ToString(obj);
                    lstSql.Add(SetSwitchedRecord(swr));
                    //如果是今天的话不需要写入调班报表

                    // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));
                }
                try
                {
                    //不需要还班 更新DriverGroup

                    if (DateTime.Now.ToString("yyyy-MM-dd") == sourceDate)
                    {
                        lstSql.Add(setDriverGroupByReplace(sourceDriver, targetReplaceDriver));
                    }
                    sqlHelper.ExecuteSqlTran(lstSql, tranId);
                }
                catch (Exception ex)
                {
                    delSwitchedRecord(Convert.ToString(obj), tranId);
                    MessageBox.Show("调班失败！" + ex.ToString());
                    return false;
                }
                //不需要还班
                //判断是不是晚班
                //获取调班那天的班次信息
                //写入计划表
                //写调班记录


            }
            return true;

        }
        /// <summary>
        /// 新的计划内调班
        /// </summary>
        /// <param name="sourceDriver"></param>
        /// <param name="targetDriver"></param>
        /// <param name="sourceDate"></param>
        /// <param name="targetDate"></param>
        /// <param name="reson"></param>
        public bool ExchangeDriverNew(string appSplane, string appTplane, string appSBackPlane, string appTBackPlane, string sourceDate, string targetDate, string reson, string cmbsouceDrive, string cmbtagerDriver)
        {
            //查找相对应的原id 和替代id

            DataTable sdtPlane = GetCrsInfoById(appSplane);

            DataTable tdtPlane = GetCrsInfoById(appTplane);
            DataTable sBackdtPlane = GetCrsInfoById(appSBackPlane);

            DataTable tBackdtPlane = GetCrsInfoById(appTBackPlane);


            string sourceDriver = "";
            string targetDriver = "";

            string sourceReplaceDriver = "";
            string targetReplaceDriver = "";
            GetDriverInToPlane(sdtPlane, ref sourceDriver, ref sourceReplaceDriver);
            GetDriverInToPlane(tdtPlane, ref targetDriver, ref targetReplaceDriver);
            //if (cmbsouceDrive == sourceDriver)
            //{
            //    targetReplaceDriver = targetDriver;
            //}




            //还班那天的信息

            string sourcebackDriver = "";
            string targetbackDriver = "";
            string sourcebackReplaceDriver = "";
            string targetbackReplaceDriver = "";

            GetDriverInToPlane(sBackdtPlane, ref sourcebackDriver, ref sourcebackReplaceDriver);
            GetDriverInToPlane(tBackdtPlane, ref targetbackDriver, ref targetbackReplaceDriver);

            //if (cmbtagerDriver==targetbackDriver)
            //{
            //    sourcebackReplaceDriver = sourcebackDriver;
            //}



            //申请司机申请当天的计划信息
            // DataTable sdtPlane = GetDtCrsInfo(sourceDriver, sourceDate);
            //替班司机申请当天的计划信息
            // DataTable tdtPlane = GetDtCrsInfo(targetDriver, sourceDate);

            ArrayList lstSql = new ArrayList();
            if (sdtPlane == null)
            {
                MessageBox.Show("申请司机" + sourceDate + "没有排班记录！");
                return false;
            }
            if (tdtPlane == null)
            {
                MessageBox.Show("替班司机" + sourceDate + "没有排班记录！");
                return false;
            }
            //判断司机今天是否已经存在调班记录 如果存在 先要求删除
            //DataTable dtSSwitch = GetdtSwitchedRecordByPlane(sourceDriver, sourceDate);
            //if (dtSSwitch.Rows.Count > 0)
            //{
            //    MessageBox.Show("申请司机今天已经存在调班记录，请先取消调班");
            //    return;
            //}
            //DataTable dtTSwitch = GetdtSwitchedRecordByPlane(targetDriver, sourceDate);
            //if (dtSSwitch.Rows.Count > 0)
            //{
            //    MessageBox.Show("替班司机今天已经存在调班记录，请先取消调班");
            //    return;
            //}

            if (!string.IsNullOrEmpty(targetDate))
            {
                ////需要还班
                //DataTable sBackdtPlane = GetDtCrsInfo(sourceDriver, targetDate);
                ////替班司机申请当天的计划信息
                //DataTable tBackdtPlane = GetDtCrsInfo(targetDriver, targetDate);

                if (sBackdtPlane.Rows.Count == 0)
                {
                    MessageBox.Show("申请司机" + targetDriver + "没有排班记录！");
                }
                if (tBackdtPlane.Rows.Count == 0)
                {
                    MessageBox.Show("替班司机" + targetDriver + "没有排班记录！");
                    return false;
                }
                SwitchedRecord swr = new SwitchedRecord();
                swr.sr_applicant = sourceReplaceDriver;
                swr.sr_SouceApplicant = sourceDriver;
                swr.sr_changer = targetReplaceDriver;
                swr.sr_SouceChanger = targetDriver;
                swr.sr_reason = reson;
                swr.sr_appdate = sourceDate;
                swr.sr_appnum = sdtPlane.Rows[0]["dcdr_duty"].ToString();
                swr.sr_chgdate = targetDate;
                swr.sr_chgnum = tdtPlane.Rows[0]["dcdr_duty"].ToString(); ;
                swr.sr_appleader = "";
                swr.sr_appresult = "";
                swr.st_apppby = CONSTDATA.UserModel.ID;
                swr.st_apppbyresult = "";
                swr.sr_chgleader = "";
                swr.sr_chgleaderresult = "";
                swr.sr_chgpby = "";
                swr.sr_chgpbyresult = "";
                swr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
                swr.parents = "";
                swr.sr_plantime = "";
                swr.tg_plantime = "";
                swr.is_tmp_exchange = "0";
                swr.sr_applicant_dgid = "";
                swr.sr_changer_dgid = "";
                swr.applyDayAppMonthID = appSplane;
                swr.backToDayBackMonthID = appTBackPlane;
                //判断还班和调班是否是同一天(写入报表的方式不一样)
                if (sourceDate == targetDate)
                {
                    //插入调班记录
                    if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate) == false)
                    {
                        MessageBox.Show("调班后申请司机组没有电客车司机");
                        return false;
                    }
                    if (IsCanChangeByDriverType(targetDriver, sourceDriver, sourceDate) == false)
                    {
                        MessageBox.Show("调班后替代司机组没有电客车司机");
                        return false;
                    }


                    string insertSwitchedRecord = SetSwitchedRecord(swr);
                    object obj = sqlHelper.GetSingle(insertSwitchedRecord);
                    // lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sourceDriver, targetDriver, sourceDate));

                    lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, sourceDate, "0"));

                    if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3" && tdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {
                        DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //替班司机申请当天的计划信息
                        DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                        if (sBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("调班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (tBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (IsCanChangeByDriverType(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd")) == false)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("调班后申请司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                            return false;
                        }

                        //有排班计划进行调班
                        swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_appnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0][0].ToString(); ;
                        swr.backToDayBackMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                        swr.parents = Convert.ToString(obj);
                        lstSql.Add(SetSwitchedRecord(swr));

                        //    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                        lstSql.Add(setMonthPlaneExchangeInfoAndReplaceBySameDay(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));

                    }
                    else
                        //判断两个班次是否有晚班的
                        if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                        {
                            //DataTable dtSSwitchNextDay = GetdtSwitchedRecordByPlane(sourceDriver,Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                            //if (dtSSwitch.Rows.Count > 0)
                            //{
                            //    MessageBox.Show("申请司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                            //    return;
                            //}
                            //DataTable dtTSwitchNextDay = GetdtSwitchedRecordByPlane(targetDriver,Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                            //if (dtSSwitch.Rows.Count > 0)
                            //{
                            //    MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                            //    return;
                            //}
                            //申请司机是晚班
                            DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                            //替班司机申请当天的计划信息
                            DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                            if (sBackNextDaydtPlane == null)
                            {
                                delSwitchedRecord(Convert.ToString(obj));
                                MessageBox.Show("调班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                return false;
                            }
                            if (tBackNextDaydtPlane == null)
                            {
                                delSwitchedRecord(Convert.ToString(obj));
                                MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                return false;
                            }
                            if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate) == false)
                            {
                                delSwitchedRecord(Convert.ToString(obj));
                                MessageBox.Show("调班后申请司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                                return false;
                            }

                            //有排班计划进行调班
                            swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                            swr.sr_appnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                            swr.sr_chgnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                            swr.sr_chgdate = "";
                            swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0][0].ToString(); ;
                            // swr.backToDayBackMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                            // swr.applyDayAppMonthID = sdtPlane.Rows[0]["dcdr_cls_id"].ToString();
                            swr.parents = Convert.ToString(obj);
                            lstSql.Add(SetSwitchedRecord(swr));

                            //    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                            lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));



                        }
                        else
                            if (tBackdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                            {
                                //DataTable dtSSwitchNextDay = GetdtSwitchedRecordByPlane(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                                //if (dtSSwitch.Rows.Count > 0)
                                //{
                                //    MessageBox.Show("申请司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                                //    return;
                                //}
                                //DataTable dtTSwitchNextDay = GetdtSwitchedRecordByPlane(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                                //if (dtSSwitch.Rows.Count > 0)
                                //{
                                //    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                                //    return;
                                //}

                                //还班
                                //申请司机当天为晚班 需要调早班
                                DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                                //替班司机申请当天的计划信息
                                DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                                if (sBackNextDaydtPlane == null)
                                {
                                    delSwitchedRecord(Convert.ToString(obj));
                                    MessageBox.Show("调班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                    return false;
                                }
                                if (tBackNextDaydtPlane == null)
                                {
                                    delSwitchedRecord(Convert.ToString(obj));
                                    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                                    return false;
                                }
                                if (IsCanChangeByDriverType(targetDriver, sourceDriver, targetDate) == false)
                                {
                                    delSwitchedRecord(Convert.ToString(obj));
                                    MessageBox.Show("调班后替班司机组" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                                    return false;
                                }
                                swr.sr_appdate = Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd");
                                swr.sr_applicant = targetReplaceDriver;
                                swr.sr_changer = sourceReplaceDriver;
                                swr.sr_appnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                                swr.sr_chgnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                                swr.applyDayAppMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                                swr.sr_chgdate = "";
                                swr.parents = Convert.ToString(obj);
                                lstSql.Add(SetSwitchedRecord(swr));

                                // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "2"));
                                lstSql.Add(lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, targetReplaceDriver, sourceDriver, sourceReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0")));

                            }
                    try
                    {
                        if (DateTime.Now.ToString("yyyy-MM-dd") == sourceDate)
                        {
                            lstSql.Add(setDriverGroupByReplace(sourceDriver, targetDriver, targetDriver, sourceDriver));
                        }
                        sqlHelper.ExecuteSqlTran(lstSql);

                    }
                    catch
                    {
                        delSwitchedRecord(Convert.ToString(obj));
                        MessageBox.Show("调班失败！");
                        return false;
                    }


                }
                else
                {
                    if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate) == false)
                    {
                        MessageBox.Show("调班后申请司机组没有电客车司机");
                        return false;
                    }
                    if (IsCanChangeByDriverType(targetDriver, sourceDriver, targetDate) == false)
                    {
                        MessageBox.Show("调班后替代司机组没有电客车司机");
                        return false;
                    }

                    //写调班记录
                    string insertSwitchedRecord = SetSwitchedRecord(swr);
                    object obj = sqlHelper.GetSingle(insertSwitchedRecord);
                    //更改调班当天的月计划
                    // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, sourceDate, "1"));
                    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, sourceDate, "0"));
                    //更改还班当天的月计划
                    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetbackDriver, targetbackReplaceDriver, sourcebackDriver, sourcebackReplaceDriver, targetDate, "1"));
                    //lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, sourceDriver, targetDate, "2"));
                    //判断当天是不是晚班 如果是晚班的话 对白班进行调班

                    //获取当天被调班司机的班次
                    if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {

                        //申请司机当天为晚班 需要调早班
                        DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //替班司机申请当天的计划信息
                        DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                        if (sBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("调班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (tBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("替班司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate) == false)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("调班后申请司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                            return false;
                        }
                        //生成第二天的调班计划报表信息
                        swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_appnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.applyDayAppMonthID = sBackNextDaydtPlane.Rows[0][0].ToString();
                        swr.sr_chgdate = "";
                        swr.parents = Convert.ToString(obj);
                        lstSql.Add(SetSwitchedRecord(swr));
                        //lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));
                        lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));

                    }
                    //判断还班那天
                    if (tBackdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {
                        //DataTable dtSSwitchNextDay = GetdtSwitchedRecordByPlane(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //if (dtSSwitch.Rows.Count > 0)
                        //{
                        //    MessageBox.Show("申请司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                        //    return;
                        //}
                        //DataTable dtTSwitchNextDay = GetdtSwitchedRecordByPlane(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //if (dtSSwitch.Rows.Count > 0)
                        //{
                        //    MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "已经存在调班记录，请先取消调班");
                        //    return;
                        //}
                        //还班
                        //申请司机当天为晚班 需要调早班
                        DataTable sBackNextDaydtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                        //替班司机申请当天的计划信息
                        DataTable tBackNextDaydtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"));
                        if (sBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("调班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (tBackNextDaydtPlane == null)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("替班司机" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "没有排班计划");
                            return false;
                        }
                        if (IsCanChangeByDriverType(targetDriver, sourceDriver, targetDate) == false)
                        {
                            delSwitchedRecord(Convert.ToString(obj));
                            MessageBox.Show("调班后替班司机组" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "没有电客车司机");
                            return false;
                        }
                        swr.sr_appdate = Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd");
                        swr.sr_applicant = targetReplaceDriver;
                        swr.sr_changer = sourceReplaceDriver;
                        swr.sr_appnum = tBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgnum = sBackNextDaydtPlane.Rows[0]["dcdr_duty"].ToString();
                        swr.sr_chgdate = "";
                        swr.applyDayAppMonthID = tBackNextDaydtPlane.Rows[0][0].ToString();
                        swr.parents = Convert.ToString(obj);
                        lstSql.Add(SetSwitchedRecord(swr));
                        // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetDriver, sourceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "2"));
                        lstSql.Add(setMonthPlaneExchangeInfoAndReplace(targetbackDriver, targetbackReplaceDriver, sourcebackDriver, sourcebackReplaceDriver, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                    }
                    try
                    {
                        if (DateTime.Now.ToString("yyyy-MM-dd") == sourceDate)
                        {
                            lstSql.Add(setDriverGroupByReplace(sourceDriver, targetDriver));
                        }
                        if (DateTime.Now.ToString("yyyy-MM-dd") == targetDate)
                        {
                            lstSql.Add(setDriverGroupByReplace(targetDriver, sourceDriver));
                        }
                        sqlHelper.ExecuteSqlTran(lstSql);
                    }
                    catch (Exception ex)
                    {
                        delSwitchedRecord(Convert.ToString(obj));
                        MessageBox.Show("调班失败！" + ex.ToString());
                        return false;
                    }
                }



            }
            else
            {

                // ChkDriversTypeInGroup(sourceDriver,targetDriver,sourceDate)
                if (IsCanChangeByDriverType(sourceDriver, targetDriver, sourceDate) == false)
                {
                    MessageBox.Show("调班后申请司机组没有电客车司机");
                    return false;
                }
                //写入报表

                //  lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, sourceDate, "1"));
                lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, sourceDate, "0"));


                SwitchedRecord swr = new SwitchedRecord();
                swr.sr_applicant = sourceReplaceDriver;
                swr.sr_SouceApplicant = sourceDriver;
                swr.sr_changer = targetReplaceDriver;
                swr.sr_SouceChanger = targetDriver;
                swr.sr_reason = reson;
                swr.sr_appdate = sourceDate;
                swr.sr_appnum = sdtPlane.Rows[0]["dcdr_duty"].ToString();
                swr.sr_chgdate = "";
                swr.sr_chgnum = tdtPlane.Rows[0]["dcdr_duty"].ToString(); ;
                swr.sr_appleader = "";
                swr.sr_appresult = "";
                swr.st_apppby = CONSTDATA.UserModel.ID;
                swr.st_apppbyresult = "";
                swr.sr_chgleader = "";
                swr.sr_chgleaderresult = "";
                swr.sr_chgpby = "";
                swr.sr_chgpbyresult = "";
                swr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
                swr.parents = "";
                swr.sr_plantime = "";
                swr.tg_plantime = "";
                swr.is_tmp_exchange = "0";
                swr.sr_applicant_dgid = "";
                swr.sr_changer_dgid = "";
                swr.applyDayAppMonthID = appSplane;

                string insertSwitchedRecord = SetSwitchedRecord(swr);
                object obj = sqlHelper.GetSingle(insertSwitchedRecord);

                if (sdtPlane.Rows[0]["dcdr_cls_id"].ToString() == "3")
                {
                    //夜班 写第二天的调班记录
                    DataTable sNextdtPlane = GetDtCrsInfo(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                    DataTable tNextdtPlane = GetDtCrsInfo(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                    if (sNextdtPlane == null)
                    {
                        delSwitchedRecord(Convert.ToString(obj));
                        MessageBox.Show("申请司机" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "早班没有排班计划");
                        return false;
                    }
                    swr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
                    swr.sr_appnum = sNextdtPlane.Rows[0]["dcdr_duty"].ToString();
                    swr.sr_chgnum = tNextdtPlane.Rows[0]["dcdr_duty"].ToString();
                    swr.applyDayAppMonthID = sNextdtPlane.Rows[0][0].ToString();
                    swr.parents = Convert.ToString(obj);
                    lstSql.Add(SetSwitchedRecord(swr));
                    //如果是今天的话不需要写入调班报表

                    // lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1"));

                    lstSql.Add(setMonthPlaneExchangeInfoAndReplace(sourceDriver, sourceReplaceDriver, targetDriver, targetReplaceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "0"));
                }
                try
                {
                    //不需要还班 更新DriverGroup

                    if (DateTime.Now.ToString("yyyy-MM-dd") == sourceDate)
                    {
                        lstSql.Add(setDriverGroupByReplace(sourceDriver, targetReplaceDriver));
                    }
                    sqlHelper.ExecuteSqlTran(lstSql);
                }
                catch (Exception ex)
                {
                    delSwitchedRecord(Convert.ToString(obj));
                    MessageBox.Show("调班失败！" + ex.ToString());
                    return false;
                }
                //不需要还班
                //判断是不是晚班
                //获取调班那天的班次信息
                //写入计划表
                //写调班记录


            }
            return true;

        }

        //public void ExchangeDriver(string sourceDriver, string targetDriver,string sourceDate,string targetDate,string reson)
        //{



        //    string sourceReMark = "";
        //    string targeReMark = "";
        //    string parentsid = "";
        //    //查找原先对应的交路
        //    //string sourceSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + sourceDate + "' and dcdr_userID='" + sourceDriver + "'";
        //    //DataTable dtSource = sqlHelper.SelectDt(sourceSql);
        //    //if (dtSource.Rows.Count > 0)
        //    //{
        //    //    sourceReMark = dtSource.Rows[0][0].ToString();
        //    //}

        //    //因为计划调班不允许多次调班，因此判断司机是否有调班记录，如果则提示，并且不允许调班



        //    sourceReMark = GetCrossRemark(sourceDate, sourceDriver);
        //    string sqlInsetr = "";
        //    SwitchedRecord sr = new SwitchedRecord();
        //    sr.sr_applicant = sourceDriver;
        //    sr.sr_changer = targetDriver;
        //    sr.sr_appdate = sourceDate;


        //    sr.st_apppby = CONSTDATA.UserModel.ID;
        //    sr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
        //    sr.sr_appresult = "1";
        //    sr.st_apppbyresult = "1";
        //    sr.sr_chgpbyresult = "1";
        //    sr.sr_chgleaderresult = "1";
        //    sr.sr_appnum = sourceReMark;

        //    sr.sr_reason = reson;

        //    if (!string.IsNullOrEmpty(targetDate))
        //    {
        //        //string targetSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + targetDate + "' and dcdr_userID='" + targetDriver + "'";
        //        //DataTable dttargetSql = sqlHelper.SelectDt(targetSql);
        //        //if (dttargetSql.Rows.Count > 0)
        //        //{
        //        //    targeReMark = dttargetSql.Rows[0][0].ToString();
        //        //}
        //        targeReMark = GetCrossRemark(targetDate, targetDriver);
        //        sr.sr_chgnum = targeReMark;
        //        sr.sr_chgdate = targetDate;

        //         sqlInsetr = "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate, sr_chgdate,st_apppby,sr_approvaldate,sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum,sr_chgnum,sr_reason) "+
        //             " values('" + sourceDriver + "','" + targetDriver + "','" + sourceDate + "','" + targetDate + "','" +
        //             Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + 
        //             sourceReMark + "','" + targeReMark + "','" + reson + "');select @@IDENTITY";
        //    }
        //    else
        //    {
        //         sqlInsetr = "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate, st_apppby,sr_approvaldate,sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum,sr_reason) values('" + sourceDriver + "','"
        //      + targetDriver + "','" + sourceDate + "','" + Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + sourceReMark + "','" + reson + "');select @@IDENTITY";

        //    }

        //   object obj=sqlHelper.GetSingle(SetSwitchedRecord(sr));

        //    //更新轮班计划
        //    //不需要替换的
        //    if (sourceDate == targetDate)
        //    {
        //        //如果是同一天
        //        exchangeMonthsClassBySameDay(sourceDriver, targetDriver, sourceDate);
        //        //setNexDayByZB(sourceDriver, targetDriver, sourceDate, reson,Convert.ToString(obj));
        //        //setNexDayByZB(targetDriver, sourceDriver, sourceDate, reson, Convert.ToString(obj));
        //        setNexDayByZB(sourceDriver, targetDriver, sourceDate,sourceDate, reson,Convert.ToString(obj));
        //    }
        //    else
        //    {
        //        if (string.IsNullOrEmpty(targetDate))
        //        {
        //            exchangeMonthsClass(sourceDriver, targetDriver, sourceDate, "1");
        //            setNexDayByZB(sourceDriver, targetDriver, sourceDate, reson, Convert.ToString(obj),null,null);

        //        }
        //        else
        //        {
        //            exchangeMonthsClass(sourceDriver, targetDriver, sourceDate, "1");

        //            //还班
        //            exchangeMonthsClass(targetDriver, sourceDriver, targetDate, "2");
        //            //setNexDayByZB(targetDriver, sourceDriver, sourceDate, reson,Convert.ToString(obj));
        //            setNexDayByZB(sourceDriver, targetDriver, sourceDate,targetDate, reson, Convert.ToString(obj));
        //        }

        //        //
        //        if (sourceDate == DateTime.Now.ToString("yyyy-MM-dd"))
        //        {
        //            string sql = " update drivergroup set replacedriver=" + targetDriver + " where dgrp_user_id="+sourceDriver;
        //            sqlHelper.GetSingle(sql);
        //        }
        //    }


        //}

        public string GetCrossRemark(string sourceDate, string sourceDriver)
        {
            string sourceReMark = "";
            string sourceSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + sourceDate + "' and dcdr_userID='" + sourceDriver + "'";
            DataTable dtSource = sqlHelper.SelectDt(sourceSql);
            if (dtSource.Rows.Count > 0)
            {
                sourceReMark = dtSource.Rows[0][0].ToString();
            }
            return sourceReMark;
        }
        #endregion

        public bool IsBackMove(string souceId, string tageterid, bool ask = true, bool isSetNull = true)
        {
            //判断两人各自今天是否存在调班记录
            /*  DataTable dtSourceSwitch = GetdtSwitchedRecord(souceId, DateTime.Now.ToString("yyyy-MM-dd"));
              DataTable dtTageterSwitch = GetdtSwitchedRecord(tageterid, DateTime.Now.ToString("yyyy-MM-dd"));
              ArrayList arr = new ArrayList();

              if (dtSourceSwitch.Rows.Count > 0)
              {
                  arr.Add(souceId);

              }
              if (dtTageterSwitch.Rows.Count > 0)
              {
                  arr.Add(tageterid);
              }

              if (arr.Count > 0)
              {
                  string messageName = "";
                  foreach (string s in arr)
                  {
                      DataTable dtUserName = GetSystemuser(s);
                      if (dtUserName.Rows.Count > 0)
                      {
                          messageName = messageName + " " + dtUserName.Rows[0]["user_view_name"].ToString();
                      }

                  }
                  MessageBoxResult dr = MessageBoxHelper.ShowYesNoAndTips(messageName + "已存在调班信息 是否删除原先调班记录");
                  if (dr == MessageBoxResult.Yes)
                  {
                      //确定 
                      ArrayList lstSql = new ArrayList();
                      SetMoveBackMain(dtSourceSwitch, ref lstSql);
                      SetMoveBackMain(dtTageterSwitch, ref lstSql);
                      sqlHelper.ExecuteSqlTran(lstSql);
                      return true;
                  }
                  else
                  {
                      return false;
                  }
              }
          
              return true;*/
            return IsBackMove(souceId, tageterid, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"), ask, isSetNull);
        }

        public bool IsBackMove(string souceId, string tageterid, string sourcedate, string tagetDate, bool ask = true, bool isSetNull = true)
        {
            if (string.IsNullOrEmpty(tagetDate))
            { }
            else
            {
                tagetDate = Convert.ToDateTime(tagetDate).ToString("yyyy-MM-dd");
            }

            if (string.IsNullOrEmpty(sourcedate))
            { }
            else
            {
                sourcedate = Convert.ToDateTime(sourcedate).ToString("yyyy-MM-dd");
            }

            //判断两人各自今天是否存在调班记录
            DataTable dtSourceSwitch = GetdtSwitchedRecord(souceId, sourcedate);
            DataTable dtTageterSwitch = GetdtSwitchedRecord(tageterid, tagetDate);
            ArrayList arr = new ArrayList();

            if (dtSourceSwitch.Rows.Count > 0)
            {
                arr.Add(souceId);

            }
            if (dtTageterSwitch.Rows.Count > 0)
            {
                arr.Add(tageterid);
            }

            if (arr.Count > 0)
            {
                string messageName = "";
                foreach (string s in arr)
                {
                    DataTable dtUserName = GetSystemuser(s);
                    if (dtUserName.Rows.Count > 0)
                    {
                        messageName = messageName + " " + dtUserName.Rows[0]["user_view_name"].ToString();
                    }

                }

                MessageBoxResult dr;
                if (ask)
                    dr = MessageBoxHelper.ShowYesNoAndTips(messageName + "已存在调班信息 是否删除原先调班记录");
                else
                    dr = MessageBoxResult.Yes;
                if (dr == MessageBoxResult.Yes)
                {
                    //确定 
                    ArrayList lstSql = new ArrayList();
                    //如果是今天清空driverGroup
                    if (isSetNull)
                    {
                        if (DateTime.Now.ToString("yyyy-MM-dd") == sourcedate)
                        {
                            SetReplaceDriveNull(souceId, ref lstSql);
                        }
                        if (DateTime.Now.ToString("yyyy-MM-dd") == tagetDate)
                        {
                            SetReplaceDriveNull(tageterid, ref lstSql);
                        }
                    }
                    SetMoveBackMain(dtSourceSwitch, ref lstSql);
                    SetMoveBackMain(dtTageterSwitch, ref lstSql);
                    sqlHelper.ExecuteSqlTran(lstSql);
                    return true;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 获取这个月的
        /// </summary>
        /// <returns></returns>
        public DataTable GetSwitchRecordByMonth(string date, string userid)
        {
            DateTime dateTime = Convert.ToDateTime(date);
            string startDay = dateTime.Year + "-" + dateTime.Month + "-" + "01";
            string endDay = dateTime.Year + "-" + dateTime.Month + "-" + DateTime.DaysInMonth(dateTime.Year, dateTime.Month);

            string str = "select d.dcdr_userID, d.dcdr_userName,d.dcdr_date,dt.dcdr_userID, dt.dcdr_userName,dt.dcdr_date,d.dcdr_team,dt.dcdr_team from dbo.SwitchedRecord s left join DriverCombineCrossingRoadPlane d on s.sr_SouceApplicant=d.dcdr_userID and s.sr_appdate=d.dcdr_date left join DriverCombineCrossingRoadPlane dt on s.sr_SouceChanger=dt.dcdr_userID and s.sr_appdate=dt.dcdr_date where dt.dcdr_team<>d.dcdr_team and (sr_appdate between'" + startDay + "' and '" + endDay + "' ) and  (sr_applicant='" + userid + "' or sr_changer='" + userid + "')";

            return sqlHelper.SelectDt(str);
        }

        public void SetReplaceDriveNull(string useid, ref ArrayList lst)
        {
            string str = "update DriverGroup set replaceDriver=null where dgrp_user_id='" + useid + "' or replaceDriver='" + useid + "'";
            lst.Add(str);
        }


        //
        public void exchangeMonthsClass(string sourceUserid, string targetUserid, string date, string type)
        {
            string str = "替";
            //更新代替的司机
            if (type == "1")
            {
                str = "替";
            }
            else
            {
                str = "还";
            }
            string sql = "update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+DriverCombineCrossingRoadPlane.dcdr_userName+'" + str + "'+TBL.dcdr_userName +')' ,DriverCombineCrossingRoadPlane.exchangeRemark=DriverCombineCrossingRoadPlane.dcdr_userName+'" + str + "'+TBL.dcdr_userName,wHours=CONVERT(dec(18,2),ISNULL(DriverCombineCrossingRoadPlane.wHours,0) )+CONVERT(dec(18,2),isnull(TBL.wHours,0)),miles= CONVERT(dec(18,2),ISNULL( DriverCombineCrossingRoadPlane.miles ,0))+CONVERT(dec(18,2),ISNULL( tbl.miles, 0)) ,replaceDriver='" + sourceUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + sourceUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + targetUserid + "';";
            //更新需代表的司机
            sql = sql + "update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+TBL.dcdr_userName+'" + str + "'+DriverCombineCrossingRoadPlane.dcdr_userName+')' ,DriverCombineCrossingRoadPlane.exchangeRemark=TBL.dcdr_userName+'" + str + "'+DriverCombineCrossingRoadPlane.dcdr_userName,miles=0,wHours=0 ,replaceDriver='" + targetUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + targetUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + sourceUserid + "'";

            sqlHelper.ExecuteSql(sql);

        }

        public void exchangeMonthsClassBySameDay(string sourceUserid, string targetUserid, string date)
        {
            string sql = "declare @sqlmile varchar(50); declare @sqlhour varchar(50);select @sqlmile=miles,@sqlhour=wHours from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and dcdr_userID='" + sourceUserid + "';update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+TBL.dcdr_userName+'替'+DriverCombineCrossingRoadPlane.dcdr_userName +')' ,DriverCombineCrossingRoadPlane.exchangeRemark=TBL.dcdr_userName+'替'+DriverCombineCrossingRoadPlane.dcdr_userName,wHours=CONVERT(dec(18,2),isnull(TBL.wHours,0)),miles=CONVERT(dec(18,2),ISNULL( tbl.miles, 0)),replaceDriver='" + targetUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + targetUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + sourceUserid + "';update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+TBL.dcdr_userName+'还'+DriverCombineCrossingRoadPlane.dcdr_userName +')',DriverCombineCrossingRoadPlane.exchangeRemark=TBL.dcdr_userName+'还'+DriverCombineCrossingRoadPlane.dcdr_userName ,wHours=CONVERT(dec(18,2),isnull(@sqlhour,0)),miles=CONVERT(dec(18,2),ISNULL( @sqlmile, 0)) ,replaceDriver='" + sourceUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + sourceUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + targetUserid + "';";


            sqlHelper.ExecuteSql(sql);

        }


        /// <summary>
        /// 设置早班的替换人员
        /// </summary>
        //public void setNexDayByZB(string sourceDriver, string targetDriver, string sourceDate, string reson, string parents, string appDgid, string chDgid, bool isSetMontnPlane = true)
        //{
        //     //查找当前班次是否是夜班，如果是夜班的话加入一个调班记录
        //    //查找需调班人员的的班次信息
        //    string str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='"+sourceDate+"' and dcdr_userID='"+sourceDriver+"' and dcdr_cls_id='3'";
        //    DataTable dt = sqlHelper.SelectDt(str);
        //    if (dt.Rows.Count > 0)
        //    {
        //        //查找第二天的班次
        //        string strNextDay = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" +Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver + "'";
        //        DataTable dtNextDay = sqlHelper.SelectDt(strNextDay);
        //        if (dtNextDay.Rows.Count > 0)
        //        {
        //            string updateNextDay = "update DriverCombineCrossingRoadPlane set replaceDriver='"+targetDriver+"' where ID='"+dtNextDay.Rows[0][0].ToString()+"'";
        //            //插入一条调班记录
        //            sqlHelper.ExecuteSql(updateNextDay);

        //            string sourceSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) , dcdr_crossNum) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver + "'";
        //            DataTable dtSource = sqlHelper.SelectDt(sourceSql);
        //            string sourceReMark = "";
        //            if (dtSource.Rows.Count > 0)
        //            {
        //                sourceReMark = dtSource.Rows[0][0].ToString();
        //            }

        //            SwitchedRecord sr = new SwitchedRecord();
        //            sr.sr_applicant = sourceDriver;
        //            sr.sr_changer = targetDriver;
        //            sr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");

        //            sr.st_apppby = CONSTDATA.UserModel.ID;
        //            sr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
        //            sr.sr_appresult = "1";
        //            sr.st_apppbyresult = "1";
        //            sr.sr_chgpbyresult = "1";
        //            sr.sr_chgleaderresult = "1";
        //            sr.sr_appnum = sourceReMark;

        //            sr.sr_reason = reson;
        //            sr.parents = parents;
        //            sr.sr_applicant_dgid = appDgid;
        //            sr.sr_changer_dgid = chDgid;

        //    //        string sqlInsetr = 
        //    //            "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate, st_apppby,sr_approvaldate,sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum,sr_reason,parents,sr_applicant_dgid,sr_changer_dgid) "+
        //    //            " values('" + sourceDriver + "','"
        //    //+ targetDriver + "','" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "','" + Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + 
        //    //DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + sourceReMark + "','" + reson + "','"+parents+"',"+appDgid+","+chDgid+")";
        //           sqlHelper.ExecuteSql(SetSwitchedRecord(sr));
        //            //再进行一次调班
        //           if (isSetMontnPlane)
        //           {
        //               exchangeMonthsClass(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1");
        //           }

        //        }
        //    }      
        //}



        public void setNexDayByZB(string sourceDriver, string targetDriver, string sourceDate, string targetDate, string reson, string parents, bool isSetMontnPlane = true)
        {
            //查找当前班次是否是夜班，如果是夜班的话加入一个调班记录
            //查找需调班人员的的班次信息
            string str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + sourceDate + "' and dcdr_userID='" + sourceDriver + "' and dcdr_cls_id='3'";
            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                //查找第二天的班次
                string strNextDay = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver + "'";
                DataTable dtNextDay = sqlHelper.SelectDt(strNextDay);
                if (dtNextDay.Rows.Count > 0)
                {
                    string updateNextDay = "update DriverCombineCrossingRoadPlane set replaceDriver='" + targetDriver + "' where ID='" + dtNextDay.Rows[0][0].ToString() + "'";
                    //插入一条调班记录
                    sqlHelper.ExecuteSql(updateNextDay);
                    //再进行一次调班*/
                    if (isSetMontnPlane)
                    {
                        exchangeMonthsClass(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"), "1");
                    }

                }
            }

            string strtagre = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + targetDate + "' and dcdr_userID='" + targetDriver + "' and dcdr_cls_id='3'";
            DataTable dttagre = sqlHelper.SelectDt(strtagre);
            if (dttagre.Rows.Count > 0)
            {
                //查找第二天的班次
                string strNextDay = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + targetDriver + "'";
                DataTable dtNextDay = sqlHelper.SelectDt(strNextDay);
                if (dtNextDay.Rows.Count > 0)
                {
                    string updateNextDay = "update DriverCombineCrossingRoadPlane set replaceDriver='" + sourceDriver + "' where ID='" + dtNextDay.Rows[0][0].ToString() + "'";
                    //插入一条调班记录
                    sqlHelper.ExecuteSql(updateNextDay);

                    if (isSetMontnPlane)
                    {
                        exchangeMonthsClass(targetDriver, sourceDate, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), "1");
                    }

                }
            }
            if (dt.Rows.Count > 0 || dttagre.Rows.Count > 0)
            {
                string sourceSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) , dcdr_crossNum) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver + "'";
                DataTable dtSource = sqlHelper.SelectDt(sourceSql);
                string sourceReMark = "";
                if (dtSource.Rows.Count > 0)
                {
                    sourceReMark = dtSource.Rows[0][0].ToString();
                }
                string targeSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) , dcdr_crossNum) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + targetDriver + "'";
                DataTable dttager = sqlHelper.SelectDt(targeSql);
                string tagerReMark = "";
                if (dttager.Rows.Count > 0)
                {
                    tagerReMark = dttager.Rows[0][0].ToString();
                }
                string sqlInsetr = "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate,sr_chgdate,sr_chgnum,st_apppby,sr_approvaldate,sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum,sr_reason,parents) values('" + sourceDriver + "','"
        + targetDriver + "','" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "','" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "','" + tagerReMark + "','" + Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + sourceReMark + "','" + reson + "','" + parents + "')";
                sqlHelper.ExecuteSql(sqlInsetr);
            }
        }

        //public void setNexDayByZB(DriverCard sourceDriver, DriverCard targetDriver, string sourceDate, string targetDate, string reson, string parents, bool isSetMontnPlane = true)
        //{

        //    string sid = "";
        //    string tid = "";

        //    if (string.IsNullOrEmpty(sourceDriver.ReplaceDriverId))
        //    {
        //        sid = sourceDriver.Driverid;
        //    }
        //    else
        //    {
        //        sid = sourceDriver. ReplaceDriverId;
        //    }

        //    if (string.IsNullOrEmpty(targetDriver.ReplaceDriverId))
        //    {
        //        tid = targetDriver.Driverid;
        //    }
        //    else
        //    {
        //        tid = targetDriver.ReplaceDriverId;
        //    }
        //    //查找当前班次是否是夜班，如果是夜班的话加入一个调班记录
        //    //查找需调班人员的的班次信息
        //    string str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + sourceDate + "' and dcdr_userID='" + sid + "' and dcdr_cls_id='3'";
        //    DataTable dt = sqlHelper.SelectDt(str);
        //    if (dt.Rows.Count > 0)
        //    {
        //        //查找第二天的班次
        //        string strNextDay = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sid + "'";
        //        DataTable dtNextDay = sqlHelper.SelectDt(strNextDay);
        //        if (dtNextDay.Rows.Count > 0)
        //        {
        //            string updateNextDay = "update DriverCombineCrossingRoadPlane set replaceDriver='" + tid + "' where ID='" + dtNextDay.Rows[0][0].ToString() + "'";
        //            //插入一条调班记录
        //            sqlHelper.ExecuteSql(updateNextDay);


        //        }
        //    }

        //    string strtagre = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + targetDate + "' and dcdr_userID='" + tid + "' and dcdr_cls_id='3'";
        //    DataTable dttagre = sqlHelper.SelectDt(strtagre);
        //    if (dttagre.Rows.Count > 0)
        //    {
        //        //查找第二天的班次
        //        string strNextDay = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + tid + "'";
        //        DataTable dtNextDay = sqlHelper.SelectDt(strNextDay);
        //        if (dtNextDay.Rows.Count > 0)
        //        {
        //            string updateNextDay = "update DriverCombineCrossingRoadPlane set replaceDriver='" + sid + "' where ID='" + dtNextDay.Rows[0][0].ToString() + "'";
        //            //插入一条调班记录
        //            sqlHelper.ExecuteSql(updateNextDay);



        //        }
        //    }
        //    if (dt.Rows.Count > 0 || dttagre.Rows.Count > 0)
        //    {
        //        string sourceSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) , dcdr_crossNum) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver.Driverid + "'";
        //        DataTable dtSource = sqlHelper.SelectDt(sourceSql);
        //        string sourceReMark = "";
        //        if (dtSource.Rows.Count > 0)
        //        {
        //            sourceReMark = dtSource.Rows[0][0].ToString();
        //        }
        //        string targeSql = "select case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) , dcdr_crossNum) as class from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + targetDriver.Driverid + "'";
        //        DataTable dttager = sqlHelper.SelectDt(targeSql);
        //        string tagerReMark = "";
        //        if (dttager.Rows.Count > 0)
        //        {
        //            tagerReMark = dttager.Rows[0][0].ToString();
        //        }
        //        SwitchedRecord sr = new SwitchedRecord();
        //        sr.sr_applicant = sid;
        //        sr.sr_changer = tid;
        //        sr.sr_appdate = Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd");
        //        sr.sr_chgdate = Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd");
        //        sr.sr_chgnum = tagerReMark;
        //        sr.st_apppby = CONSTDATA.UserModel.ID;
        //        sr.sr_approvaldate = DateTime.Now.ToString("yyyy-MM-dd");
        //        sr.sr_appresult = "1";
        //        sr.st_apppbyresult = "1";
        //        sr.sr_chgpbyresult = "1";
        //        sr.sr_chgleaderresult = "1";
        //        sr.sr_appnum = sourceReMark;
        //        sr.sr_reason = reson;
        //        sr.parents = parents;
        //        sr.sr_applicant_dgid = sourceDriver.DriverGroupId.ToString();
        //        sr.sr_changer_dgid = targetDriver.DriverGroupId.ToString();
        //        string sqlInsetr = SetSwitchedRecord(sr);

        //        //string sqlInsetr = "insert into SwitchedRecord (sr_applicant, sr_changer,sr_appdate,sr_chgdate,sr_chgnum,st_apppby,sr_approvaldate," +
        //        //    "sr_appresult,st_apppbyresult,sr_chgpbyresult,sr_chgleaderresult,sr_appnum,sr_reason,parents) " +
        //        //    " values('" + sid + "','" + tid + "','" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "','" +
        //        //    Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "','" + tagerReMark + "','" +
        //        //    Convert.ToInt32(CONSTDATA.UserModel.ID) + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','1','1','1','1','" + sourceReMark + "','" + reson + "','" + parents + "')";
        //        sqlHelper.ExecuteSql(sqlInsetr);
        //    }
        //}

        /*  public bool IsBackMove(string souceId,string tageterid)
         {
             string strsql = "select * from SwitchedRecord where sr_appdate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and sr_chgdate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and( (sr_applicant='" + souceId + "' and sr_changer='" + tageterid + "') or (sr_applicant='" + tageterid + "' and sr_changer='" + souceId + "'))";
             DataTable dt=sqlHelper.SelectDt(strsql);
             if (dt.Rows.Count > 0)
             {
              
                 //删除历史记录
                 string strDel = " delete from SwitchedRecord where ID='"+dt.Rows[0]["ID"].ToString()+"'";
                 sqlHelper.ExecuteSql(strDel);
                 //回滚周月计划表
                 SetRemarkBack(souceId,DateTime.Now.ToString("yyyy-MM-dd"));
                 SetRemarkBack(tageterid, DateTime.Now.ToString("yyyy-MM-dd"));
                 exchangeMonthsClassBySameDayBalack(souceId, tageterid, DateTime.Now.ToString("yyyy-MM-dd"));
                 return true;
             }
             return false;

          
         }*/

        public bool IsBackMoveBySameRecord(string souceId, string tageterid)
        {
            //判断是不是互调的调回来而已
            string strsql = "select * from SwitchedRecord where sr_appdate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and ( (sr_applicant='" + souceId + "' and sr_changer='" + tageterid + "') or (sr_applicant='" + tageterid + "' and sr_changer='" + souceId + "'))";
            DataTable dt = sqlHelper.SelectDt(strsql);
            if (dt.Rows.Count > 0)
            {

                ArrayList lstSql = new ArrayList();
                SetMoveBackMain(dt, ref lstSql);
                sqlHelper.ExecuteSqlTran(lstSql);
                return true;
            }



            return false;


        }

        /// <summary>
        /// 是否回滚数据
        /// </summary>
        /// <param name="souceId"></param>
        /// <param name="tageterid"></param>
        /// <param name="souceDate"></param>
        /// <param name="tagetDate"></param>
        /// <returns></returns>
        public bool IsBackMoveBySameRecord(string souceId, string tageterid, string souceDate, string tagetDate)
        {
            //判断是不是互调的调回来而已
            string sr_chgdate = "";
            if (string.IsNullOrEmpty(tagetDate))
            {
                sr_chgdate = "sr_chgdate is null";
            }
            else
            {
                sr_chgdate = "sr_chgdate ='" + tagetDate + "'";
            }

            string strsql = "select * from SwitchedRecord where sr_applicant='" + souceId + "' and sr_appdate='" + souceDate + "' and sr_changer='" + tageterid + "' and " + sr_chgdate;
            DataTable dt = sqlHelper.SelectDt(strsql);
            if (dt.Rows.Count > 0)
            {

                ArrayList lstSql = new ArrayList();
                SetMoveBackMain(dt, ref lstSql);
                sqlHelper.ExecuteSqlTran(lstSql);
                return true;
            }



            return false;


        }



        public DataTable GetSystemuser(string id)
        {
            string str = "select user_id, user_name,user_view_name from [system_user] where user_id='" + id + "'";
            return sqlHelper.SelectDt(str);
        }

        public void SetRemarkBack(string userid, string date)
        {
            string str = "  update DriverCombineCrossingRoadPlane set dcdr_remark=case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) +' '+ISNULL(dcdr_crossAttenPlace,'')+':'+ISNULL(dcdr_crossAttenTime,'') where dcdr_userID='" + userid + "' and dcdr_date='" + date + "'";
            sqlHelper.ExecuteSql(str);
        }

        public void exchangeMonthsClassBySameDayBalack(string sourceUserid, string targetUserid, string date)
        {
            string sql = "declare @sqlmile varchar(50); declare @sqlhour varchar(50);select @sqlmile=miles,@sqlhour=wHours from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and dcdr_userID='" + sourceUserid + "';update DriverCombineCrossingRoadPlane set wHours=CONVERT(dec(18,2),isnull(TBL.wHours,0)),miles=CONVERT(dec(18,2),ISNULL( tbl.miles, 0)),replaceDriver=NULL from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + targetUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + sourceUserid + "';update DriverCombineCrossingRoadPlane set wHours=CONVERT(dec(18,2),isnull(@sqlhour,0)),miles=CONVERT(dec(18,2),ISNULL( @sqlmile, 0)) ,replaceDriver=NULL from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + sourceUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + targetUserid + "';";
            sqlHelper.ExecuteSql(sql);

        }

        public void setNexDayByZBBlack(string sourceDriver, string targetDriver, string sourceDate, string reson)
        {
            //查找当前班次是否是夜班，如果是夜班的话加入一个调班记录
            //查找需调班人员的的班次信息
            string str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + sourceDate + "' and dcdr_userID='" + sourceDriver + "' and dcdr_cls_id='3'";
            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                //查找第二天的班次
                string strNextDay = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + sourceDriver + "'";
                DataTable dtNextDay = sqlHelper.SelectDt(strNextDay);
                if (dtNextDay.Rows.Count > 0)
                {
                    //删除调班记录
                    string strsql = "select * from SwitchedRecord where sr_appdate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and sr_chgdate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and( (sr_applicant='" + sourceDriver + "' and sr_changer='" + targetDriver + "') or (sr_applicant='" + targetDriver + "' and sr_changer='" + sourceDriver + "'))";
                    DataTable dtNext = sqlHelper.SelectDt(strsql);
                    if (dtNext.Rows.Count > 0)
                    {
                        string strDel = " delete from SwitchedRecord where ID='" + dt.Rows[0]["ID"].ToString() + "'";
                        sqlHelper.ExecuteSql(strDel);
                        //回滚周月计划表
                        SetRemarkBack(sourceDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                        SetRemarkBack(targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                        // exchangeMonthsClassBySameDayBalack(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));
                    }
                    exchangeMonthsClassBySameDayBalack(sourceDriver, targetDriver, Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd"));

                }
            }
        }

        /// <summary>
        /// 判断是否有能进行轮班 1. 所选日期必须有计划 如果有夜班 需判断第二天是否计划
        /// </summary>
        /// <returns></returns>
        public bool checkNextDayHasPlane(string sourceDate, string tagDate, string sourceid, string tageid)
        {
            string date = "";
            if (string.IsNullOrEmpty(tagDate))
            {
                date = sourceDate;
            }
            else
            {
                if (Convert.ToDateTime(sourceDate) > Convert.ToDateTime(tagDate))
                {
                    date = sourceDate;
                }
                else
                {
                    date = tagDate;
                }
            }
            //查找这一天是否有排版计划


            if (IsHasPlane(date))
            {
                string str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + sourceDate + "' and dcdr_userID='" + sourceid + "' and dcdr_cls_id='3'";
                DataTable dtYB = sqlHelper.SelectDt(str);
                if (dtYB.Rows.Count > 0)
                {
                    if (!IsHasPlane(Convert.ToDateTime(sourceDate).AddDays(1).ToString("yyyy-MM-dd")))
                    {
                        return false;
                    }
                }

                if (!string.IsNullOrEmpty(tagDate))
                {

                    str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + tagDate + "' and dcdr_userID='" + tageid + "' and dcdr_cls_id='3'";
                    dtYB = sqlHelper.SelectDt(str);
                    if (dtYB.Rows.Count > 0)
                    {
                        if (!IsHasPlane(Convert.ToDateTime(tagDate).AddDays(1).ToString("yyyy-MM-dd")))
                        {
                            return false;
                        }
                    }
                }







            }
            else
            {
                return false;
            }
            return true;
        }

        public bool IsHasPlane(string date)
        {

            string isHasPlane = "select * from DriverCombineCrossingRoadPlane where dcdr_date>='" + date + "'";
            DataTable dt = sqlHelper.SelectDt(isHasPlane);
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            return false;


        }

        public string DriverClsType(string userid, string date)
        {

            string str = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and dcdr_userID='" + userid + "'";
            DataTable dt = sqlHelper.SelectDt(str);

            return dt.Rows[0]["dcdr_cls_id"].ToString();


        }

        /// <summary>
        /// 回滚周月计划里面司机组的调班记录
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="date"></param>
        public void setMonthPlaneMoveBack(string userid, string date, ref ArrayList lstSql)
        {
            string strQueryMonthplan = "select ID,dcdr_cls_id,dcdr_userID,case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) +' '+ISNULL(dcdr_crossAttenPlace,'')+':'+ISNULL(dcdr_crossAttenTime,'') as remark from dbo.DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and dcdr_userID='" + userid + "';";
            string strQueryMonthplan1 = "select ID,dcdr_cls_id,dcdr_userID,case dcdr_cls_id WHEN '0' THEN '早'  WHEN '1' THEN '休' WHEN '2' THEN '白' WHEN '3' THEN '晚' end +CONVERT(varchar(50) ,case CONVERT(varchar(50), ISNULL(dcdr_crossNum,0)) when '-1' then '(休)' when 0 then ' ' else CONVERT(varchar(50), dcdr_crossNum) end) +' '+ISNULL(dcdr_crossAttenPlace,'')+':'+ISNULL(dcdr_crossAttenTime,'') as remark from dbo.DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and replaceDriver='" + userid + "';";
            DataTable dtMonthplane = sqlHelper.SelectDt(strQueryMonthplan);
            DataTable dtMonthplane1 = sqlHelper.SelectDt(strQueryMonthplan1);


            if (dtMonthplane.Rows.Count > 0)
            {
                string remark = "";
                remark = dtMonthplane.Rows[0]["remark"].ToString();
                string updateMonthPlane = "update DriverCombineCrossingRoadPlane set dcdr_remark='" + remark + "',replaceDriver=null,exchangeRemark=null,miles=sourcemiles ,wHours=sourcewHours where ID='" + dtMonthplane.Rows[0]["ID"].ToString() + "';";
                lstSql.Add(updateMonthPlane);
                //如果是夜班 清除第二天早班的
                if (dtMonthplane.Rows[0]["dcdr_cls_id"].ToString().Trim() == "3")
                {
                    setMonthPlaneMoveBack(userid, Convert.ToDateTime(date).AddDays(1).ToString("yyyy-MM-dd"), ref lstSql);
                }
            }

            if (dtMonthplane1.Rows.Count > 0)
            {
                string remark1 = "";
                remark1 = dtMonthplane1.Rows[0]["remark"].ToString();
                string updateMonthPlane = "update DriverCombineCrossingRoadPlane set dcdr_remark='" + remark1 + "',replaceDriver=null,exchangeRemark=null,miles=sourcemiles ,wHours=sourcewHours where ID='" + dtMonthplane1.Rows[0]["ID"].ToString() + "';";
                lstSql.Add(updateMonthPlane);
                //如果是夜班 清除第二天早班的
                if (dtMonthplane.Rows[0]["dcdr_cls_id"].ToString().Trim() == "3")
                {
                    setMonthPlaneMoveBack(userid, Convert.ToDateTime(date).AddDays(1).ToString("yyyy-MM-dd"), ref lstSql);
                }
            }

        }

        /// <summary>
        /// 是否可以进行换班
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public DataTable GetdtSwitchedRecord(string userid, string date)
        {
            string strsql = "select top 1 * from SwitchedRecord where ( sr_applicant='" + userid + "' or sr_changer='" + userid + "' ) and (sr_appdate='" + date + "' or sr_chgdate='" + date + "') order by ID DESC";
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql);

            return dtSwitchedRecord;
        }
        public DataTable GetdtSwitchedRecord(string userid, string date, string tranId)
        {
            string strsql = "select top 1 * from SwitchedRecord where ( sr_applicant='" + userid + "' or sr_changer='" + userid + "' ) and (sr_appdate='" + date + "' or sr_chgdate='" + date + "') order by ID DESC";
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql, tranId);

            return dtSwitchedRecord;
        }
        /// <summary>
        /// 删除调班计划
        /// </summary>
        /// <param name="del"></param>
        /// <param name="lstSql"></param>
        /// <returns></returns>
        public void DelSwitchedRecord(string del, ref ArrayList lstSql)
        {
            string delSql = "delete from SwitchedRecord where ID='" + del + "' or parents='" + del + "'";
            lstSql.Add(delSql);
        }

        public void SetMoveBackMain(DataTable dtSwitch, ref ArrayList lstSql)
        {
            //先回滚 再清除 判断是否有早班
            //查找是否有早班记录
            if (dtSwitch.Rows.Count > 0)
            {
                string strZbSwitched = "select * from SwitchedRecord where parents='" + dtSwitch.Rows[0]["ID"] + "'";
                DataTable dtZB = sqlHelper.SelectDt(strZbSwitched);
                List<string[]> lst = new List<string[]>();

                string[] str = new string[2];
                str[0] = dtSwitch.Rows[0]["sr_applicant"].ToString();
                str[1] = dtSwitch.Rows[0]["sr_appdate"].ToString();
                lst.Add(str);
                if (!string.IsNullOrEmpty(dtSwitch.Rows[0]["sr_chgdate"].ToString()))
                {
                    string[] strChange = new string[2];
                    strChange[0] = dtSwitch.Rows[0]["sr_changer"].ToString();
                    strChange[1] = dtSwitch.Rows[0]["sr_chgdate"].ToString();
                    lst.Add(strChange);
                }
                if (dtZB.Rows.Count > 0)
                {
                    string[] strzb = new string[2];
                    strzb[0] = dtZB.Rows[0]["sr_applicant"].ToString();
                    strzb[1] = dtZB.Rows[0]["sr_appdate"].ToString();
                    lst.Add(strzb);
                    if (!string.IsNullOrEmpty(dtSwitch.Rows[0]["sr_chgdate"].ToString()))
                    {
                        string[] strZBChange = new string[2];
                        strZBChange[0] = dtZB.Rows[0]["sr_changer"].ToString();
                        strZBChange[1] = dtZB.Rows[0]["sr_chgdate"].ToString();
                        lst.Add(strZBChange);
                    }
                }
                foreach (string[] s in lst)
                {
                    setMonthPlaneMoveBack(s[0], s[1], ref lstSql);
                }
                DelSwitchedRecord(dtSwitch.Rows[0]["ID"].ToString(), ref lstSql);
            }

            //DelSwitchedRecord(dtSwitch.Rows[0]["parents"].ToString(), ref lstSql);


        }

        #region 新的调班

        /// <summary>
        /// 判断该司机是否有那天时候能进行换班 （1.那天有排版计划 2.如果是晚班 第一天有排版计划）
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public void IsCanExChange(string date, DataTable dtPlane, ref List<string> lstMessage)
        {
            DataRow[] drs = dtPlane.Select("dcdr_date='" + date + "'");
            if (drs.Length > 0)
            {

            }
            else
            {
                lstMessage.Add(date + "无排班计划");

            }

        }

        /// <summary>
        /// 获取换班所选区间内的轮班计划
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="startDay"></param>
        /// <param name="endDay"></param>
        /// <returns></returns>
        public DataTable GetDtDriverPlane(string userId, string startDay, string endDay)
        {
            string isHasPlane = "select * from dbo.DriverCombineCrossingRoadPlane where dcdr_date between '" + startDay + "' and '" + Convert.ToDateTime(endDay).AddDays(1).ToString("yyyy-MM-dd") + "' and dcdr_userID='" + userId + "'";
            DataTable dt = sqlHelper.SelectDt(isHasPlane);
            return dt;
        }



        #endregion

        #region 调班20130923
        /// <summary>
        /// 真正的司机
        /// </summary>
        /// <param name="driver"></param>
        /// <returns></returns>
        public string GetRealDriver(DriverCard driver)
        {
            if (string.IsNullOrEmpty(driver.ReplaceDriverId))
            {
                return driver.Driverid;
            }
            return driver.ReplaceDriverId;
        }

        /// <summary>
        /// 判断调班后整组司机是否有电客车司机
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="tid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public bool ChkDriversTypeInGroup(string sid, string tid)
        {
            string str = "select * from [System_User] where [USER_ID] in ( ";
            str = str + "select case when replaceDriver is null then dgrp_user_id else replaceDriver  end  as userid from DriverGroup ";
            str = str + "where dgrp_dcom_id in (select dgrp_dcom_id from DriverGroup where dgrp_user_id='" + sid + "') and dgrp_user_id<>'" + sid + "' or dgrp_user_id='" + tid + "') ";
            str = str + "and user_post =15";

            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 设置调班记录
        /// </summary>
        /// <returns></returns>
        public string SetSwitchedRecord(SwitchedRecord swr)
        {
            string insertSwitchedRecord = "insert into SwitchedRecord (";
            string field = "";
            string val = "";
            if (!string.IsNullOrEmpty(swr.sr_applicant))
            {
                field = field + ",sr_applicant";
                val = val + ",'" + swr.sr_applicant + "'";
            }

            if (!string.IsNullOrEmpty(swr.sr_changer))
            {
                field = field + ",sr_changer";
                val = val + ",'" + swr.sr_changer + "'";
            }
            if (!string.IsNullOrEmpty(swr.sr_reason))
            {
                field = field + ",sr_reason";
                val = val + ",'" + swr.sr_reason + "'";
            }
            if (!string.IsNullOrEmpty(swr.sr_appdate))
            {
                field = field + ",sr_appdate";
                val = val + ",'" + swr.sr_appdate + "'";
            }
            if (!string.IsNullOrEmpty(swr.sr_appnum))
            { field = field + ",sr_appnum"; val = val + ",'" + swr.sr_appnum + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_chgdate))
            { field = field + ",sr_chgdate"; val = val + ",'" + swr.sr_chgdate + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_chgnum))
            { field = field + ",sr_chgnum"; val = val + ",'" + swr.sr_chgnum + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_appleader))
            { field = field + ",sr_appleader"; val = val + ",'" + swr.sr_appleader + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_appresult))
            { field = field + ",sr_appresult"; val = val + ",'" + swr.sr_appresult + "'"; }
            if (!string.IsNullOrEmpty(swr.st_apppby))
            { field = field + ",st_apppby"; val = val + ",'" + swr.st_apppby + "'"; }
            if (!string.IsNullOrEmpty(swr.st_apppbyresult))
            { field = field + ",st_apppbyresult"; val = val + ",'" + swr.st_apppbyresult + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_chgleader))
            { field = field + ",sr_chgleader"; val = val + ",'" + swr.sr_chgleader + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_chgleaderresult))
            { field = field + ",sr_chgleaderresult"; val = val + ",'" + swr.sr_chgleaderresult + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_chgpby))
            { field = field + ",sr_chgpby"; val = val + ",'" + swr.sr_chgpby + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_chgpbyresult))
            { field = field + ",sr_chgpbyresult"; val = val + ",'" + swr.sr_chgpbyresult + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_approvaldate))
            { field = field + ",sr_approvaldate"; val = val + ",'" + swr.sr_approvaldate + "'"; }
            if (!string.IsNullOrEmpty(swr.parents))
            { field = field + ",parents"; val = val + ",'" + swr.parents + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_plantime))
            { field = field + ",sr_plantime"; val = val + ",'" + swr.sr_plantime + "'"; }
            if (!string.IsNullOrEmpty(swr.tg_plantime))
            { field = field + ",tg_plantime"; val = val + ",'" + swr.tg_plantime + "'"; }
            if (!string.IsNullOrEmpty(swr.is_tmp_exchange))
            { field = field + ",is_tmp_exchange"; val = val + ",'" + swr.is_tmp_exchange + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_applicant_dgid))
            { field = field + ",sr_applicant_dgid"; val = val + ",'" + swr.sr_applicant_dgid + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_changer_dgid))
            { field = field + ",sr_changer_dgid"; val = val + ",'" + swr.sr_changer_dgid + "'"; }
            if (!string.IsNullOrEmpty(swr.applyDayAppMonthID))
            { field = field + ",applyDayAppMonthID"; val = val + ",'" + swr.applyDayAppMonthID + "'"; }
            if (!string.IsNullOrEmpty(swr.backToDayBackMonthID))
            { field = field + ",backToDayBackMonthID"; val = val + ",'" + swr.backToDayBackMonthID + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_SouceApplicant))
            { field = field + ",sr_SouceApplicant"; val = val + ",'" + swr.sr_SouceApplicant + "'"; }
            if (!string.IsNullOrEmpty(swr.sr_SouceChanger))
            { field = field + ",sr_SouceChanger"; val = val + ",'" + swr.sr_SouceChanger + "'"; }
            // public string applyDayAppMonthID = "";
            // public string backToDayBackMonthID="";
            if (field.StartsWith(","))
            {
                field = field.Substring(1, field.Length - 1);
            }
            if (val.StartsWith(","))
            {
                val = val.Substring(1, val.Length - 1);
            }
            insertSwitchedRecord = insertSwitchedRecord + field + ") values (" + val + ");select @@IDENTITY";
            return insertSwitchedRecord;
        }

        public void delSwitchedRecord(string ids)
        {
            string str = " delete from SwitchedRecord where ID in (" + ids + ")";
            sqlHelper.ExecuteSql(str);
        }
        public void delSwitchedRecord(string ids, string tranId)
        {
            string str = " delete from SwitchedRecord where ID in (" + ids + ")";
            sqlHelper.ExecuteSql(str, tranId);
        }

        public string delSwitchedRecordWithParent(string ids)
        {
            string str = " delete from SwitchedRecord where ID = '" + ids + "' or parents='" + ids + "' ";
            return str;
        }

        public string UpdateSwitchedRecordWithParent(string ids)
        {
            string str = " update SwitchedRecord set sr_chgdate=null where ID = '" + ids + "'";
            return str;
        }
        /// <summary>
        /// 获取交路名称
        /// </summary>
        /// <param name="cls"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        public string GetCrossingRoad(string cls, string num)
        {
            if (string.IsNullOrEmpty(num))
            {
                num = "(休)";
            }
            if (cls == "0")
            {
                return "早" + num;
            }
            if (cls == "1")
            { return "休"; }
            if (cls == "2")
            { return "白" + num; }
            if (cls == "3")
            { return "晚" + num; }
            return "";

        }

        /// <summary>
        ///获取第二天的交路号
        /// </summary>
        /// <returns></returns>
        public string GetNextDayCrsNum(string driverId, string date)
        {
            string str = "select dcdr_duty from DriverCombineCrossingRoadPlane where dcdr_userID='" + driverId + "' and dcdr_date='" + Convert.ToDateTime(date).AddDays(1).ToString("yyyy-MM-dd") + "'"; ;
            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString();
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// 设置第二天报表的替换人员
        /// </summary>
        /// <param name="sDriver"></param>
        /// <param name="tDriver"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string setNexDayReplaceDriverByCrsPlane(string sDriver, string tDriver, string date)
        {
            date = Convert.ToDateTime(date).AddDays(1).ToString("yyyy-MM-dd");
            string updateCrsPlace = "update DriverCombineCrossingRoadPlane set replaceDriver='" + tDriver + "' where dcdr_userID='" + sDriver + "' and dcdr_date='" + date + "' ;update DriverCombineCrossingRoadPlane set replaceDriver=null where dcdr_userID=replaceDriver";
            return updateCrsPlace;
        }

        /// <summary>
        /// 获取临时调班记录
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public DataTable GetdtSwitchedRecordByTemporary(string userid, string date)
        {
            string strsql = "select top 1 * from SwitchedRecord where ( sr_applicant='" + userid + "' or sr_changer='" + userid + "' ) and (sr_appdate='" + date + "' or sr_chgdate='" + date + "') and is_tmp_exchange=1 order by ID DESC";
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql);

            return dtSwitchedRecord;
        }

        public DataTable GetdtSwitchedRecordByPlane(string userid, string date)
        {
            string strsql = "select top 1 * from SwitchedRecord where ( sr_applicant='" + userid + "' or sr_changer='" + userid + "' ) and (sr_appdate='" + date + "' or sr_chgdate='" + date + "') and is_tmp_exchange<>1 order by ID DESC";
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql);

            return dtSwitchedRecord;
        }
        /// <summary>
        /// 获取用户id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetUserIdFromDriverGroup(string id)
        {
            string str = "select * from DriverGroup where ID='" + id + "'";
            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["dgrp_user_id"].ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取计划出勤的交路信息
        /// </summary>
        /// <param name="driverId"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public DataTable GetDtCrsInfo(string driverId, string date)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + driverId + "' and dcdr_date='" + date + "'"; ;
            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count > 0)
            {
                return dt;
            }
            else
            {
                return null;
            }

        }
        public DataTable GetDtCrsInfo(string driverId, string date, string tranId)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + driverId + "' and dcdr_date='" + date + "'"; ;
            DataTable dt = sqlHelper.SelectDt(str, tranId);
            if (dt.Rows.Count > 0)
            {
                return dt;
            }
            else
            {
                return null;
            }

        }


        /// <summary>
        /// 设置月计划报表的替换信息和替换人员
        /// </summary>
        /// <param name="sourceUserid"></param>
        /// <param name="targetUserid"></param>
        /// <param name="date"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string setMonthPlaneExchangeInfoAndReplace(string sourceUserid, string targetUserid, string date, string type)
        {
            string str = "替";
            //更新代替的司机
            if (type == "1")
            {
                str = "替";
            }
            else
            {
                str = "还";
            }
            string sql = "update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+DriverCombineCrossingRoadPlane.dcdr_userName+'" + str + "'+TBL.dcdr_userName +')' ,DriverCombineCrossingRoadPlane.exchangeRemark=DriverCombineCrossingRoadPlane.dcdr_userName+'" + str + "'+TBL.dcdr_userName,wHours=CONVERT(dec(18,2),ISNULL(DriverCombineCrossingRoadPlane.wHours,0) )+CONVERT(dec(18,2),isnull(TBL.wHours,0)),miles= CONVERT(dec(18,2),ISNULL( DriverCombineCrossingRoadPlane.miles ,0))+CONVERT(dec(18,2),ISNULL( tbl.miles, 0)) ,replaceDriver='" + sourceUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + sourceUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + targetUserid + "';";
            //更新需代表的司机
            sql = sql + "update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+TBL.dcdr_userName+'" + str + "'+DriverCombineCrossingRoadPlane.dcdr_userName+')' ,DriverCombineCrossingRoadPlane.exchangeRemark=TBL.dcdr_userName+'" + str + "'+DriverCombineCrossingRoadPlane.dcdr_userName,miles=0,wHours=0 ,replaceDriver='" + targetUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + targetUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + sourceUserid + "';";

            return sql;
        }

        public string setMonthPlaneExchangeInfoAndReplace(string sourceUserid, string sRealyDriver, string targetUserid, string tRealyDriver, string date, string type)
        {

            // --更新申请司机的代班人
            string str = " update DriverCombineCrossingRoadPlane set replaceDriver='" + tRealyDriver + "',isback=" + type + " where dcdr_userID='" + sourceUserid + "' and dcdr_date='" + date + "' ;";
            str = str + setMonthPlaneInfoByDriverIDandDate(sRealyDriver, date);
            str = str + setMonthPlaneInfoByDriverIDandDate(tRealyDriver, date);

            //--更新申请司机的公里数和时间
            /*  str = str + "declare @smile varchar(500); set @smile=0;";
              str = str + "declare @shouse varchar(500); set @shouse=0; ";
           str = str + "select @smile= SUM( CONVERT(dec(18,2),ISNULL(sourcemiles ,0))),@shouse= SUM( CONVERT(dec(18,2),ISNULL(sourcewHours ,0)))from DriverCombineCrossingRoadPlane where ( (dcdr_userID='" + sRealyDriver + "' and replaceDriver is null) or replaceDriver ='" + sRealyDriver + "') and dcdr_date='" + date + "';";

           //--更新申请司机的代班信息
       
           str = str + "select s.user_view_name +case isback when 1 then '还' else '替' end +dcdr.dcdr_userName+',' ex into #t  from DriverCombineCrossingRoadPlane dcdr left join [System_User] s on dcdr.replaceDriver=s.user_id where ((dcdr_userID='" + sRealyDriver + "' and replaceDriver is not null and replaceDriver not in (select dcdr_userID from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and replaceDriver='" + sRealyDriver + "') ) or (replaceDriver ='" + sRealyDriver + "' )) and dcdr_date='" + date + "';";
           str=str+"declare @sEx varchar(500);";
           str=str+"select @sEx= isnull(@sEx, '')+ex from #t ";
           str=str+"group by ex order by ex;";
           str=str+"drop table #t;";
           //str = str + "update DriverCombineCrossingRoadPlane set miles=0 ,wHours=0,exchangeRemark=null where dcdr_date='" + date + "' and dcdr_userID='" + sRealyDriver + "';";
           str=str+"update DriverCombineCrossingRoadPlane set miles=@smile ,wHours=@shouse,exchangeRemark=@sEx where dcdr_date='"+date+"' and dcdr_userID='"+sRealyDriver+"';";*/

            //--更新代班司机的公里数和时间

            /*  str = str + "declare @smilet varchar(500);set @smilet=0;";
              str = str + "declare @shouset varchar(500); set @shouset=0;";
              str = str + "select @smilet= SUM( CONVERT(dec(18,2),ISNULL(sourcemiles ,0))),@shouset= SUM( CONVERT(dec(18,2),ISNULL(sourcewHours ,0)))from DriverCombineCrossingRoadPlane where ((dcdr_userID='"+tRealyDriver+"' and replaceDriver is null) or replaceDriver ='"+tRealyDriver+"') and  dcdr_date='" + date + "';";

              //--更新代班司机的代班信息

              str = str + "select s.user_view_name +case isback when 1 then '还' else '替' end +dcdr.dcdr_userName+',' ex into #t1  from DriverCombineCrossingRoadPlane dcdr left join [System_User] s on dcdr.replaceDriver=s.user_id where ((dcdr_userID='" + tRealyDriver + "' and replaceDriver is not null and replaceDriver not in (select dcdr_userID from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and replaceDriver='" + tRealyDriver + "')) or replaceDriver ='" + tRealyDriver + "' ) and dcdr_date='" + date + "';";
              str=str+"declare @tEx varchar(500);";
              str=str+"select @tEx= isnull(@tEx, '')+ex from #t1 ";
              str=str+"group by ex order by ex;";
              str=str+"drop table #t1;";
             // str = str + "update DriverCombineCrossingRoadPlane set miles=0 ,wHours=0,exchangeRemark=null where dcdr_date='" + date + "' and dcdr_userID='" + tRealyDriver + "';";
              str = str + "update DriverCombineCrossingRoadPlane set miles=@smilet ,wHours=@shouset,exchangeRemark=@tEx where dcdr_date='" + date + "' and dcdr_userID='" + tRealyDriver + "';";*/

            return str;
        }

        public static string setMonthPlaneInfoByDriverIDandDate(string tRealyDriver, string date)
        {
            //--更新代班司机的公里数和时间
            string str = "  ";

            str = str + "declare @smilet" + tRealyDriver + " varchar(500);set @smilet" + tRealyDriver + "=0;";
            str = str + "declare @shouset" + tRealyDriver + " varchar(500); set @shouset" + tRealyDriver + "=0;";
            //str = str + "select @smilet" + tRealyDriver + "= SUM( CONVERT(dec(18,2),ISNULL(sourcemiles ,0))),@shouset" + tRealyDriver + "= SUM( CONVERT(dec(18,2),ISNULL(sourcewHours ,0)))from DriverCombineCrossingRoadPlane where ((dcdr_userID='" + tRealyDriver + "' and replaceDriver is null) or replaceDriver ='" + tRealyDriver + "') and  dcdr_date='" + date + "';";

            str = str + "select @smilet" + tRealyDriver + "= SUM( CONVERT(dec(18,2),ISNULL(sourcemiles ,0))),@shouset" + tRealyDriver + "= SUM( CONVERT(dec(18,2),ISNULL(sourcewHours ,0)))from DriverCombineCrossingRoadPlane where ((dcdr_userID='" + tRealyDriver + "' and replaceDriver is null) or replaceDriver ='" + tRealyDriver + "') and  dcdr_date='" + date + "' and ID not in ( select ID from DriverCombineCrossingRoadPlane sd where sd.dcdr_userID in( select sr_SouceChanger from SwitchedRecord s left join DriverCombineCrossingRoadPlane da on da.dcdr_userID=s.sr_SouceApplicant and s.sr_appdate=da.dcdr_date left join DriverCombineCrossingRoadPlane dc on dc.dcdr_userID=s.sr_SouceChanger and s.sr_appdate=dc.dcdr_date where sr_appdate='" + date + "' and (sr_changer='" + tRealyDriver + "') and sr_chgdate is null and da.dcdr_team=dc.dcdr_team) and sd.dcdr_date='" + date + "' );";


            //--更新代班司机的代班信息

            //str = str + "select s.user_view_name +case isback when 1 then '还' else '替' end +dcdr.dcdr_userName+',' ex into #t1" + tRealyDriver + "  from DriverCombineCrossingRoadPlane dcdr left join [System_User] s on dcdr.replaceDriver=s.user_id where ((dcdr_userID='" + tRealyDriver + "' and replaceDriver is not null and replaceDriver not in (select dcdr_userID from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and replaceDriver='" + tRealyDriver + "')) or replaceDriver ='" + tRealyDriver + "' ) and dcdr_date='" + date + "';";
            str = str + "select s.user_view_name +case isback when 1 then '还' else '替' end +dcdr.dcdr_userName+',' ex into #t1" + tRealyDriver + "  from DriverCombineCrossingRoadPlane dcdr left join [System_User] s on dcdr.replaceDriver=s.user_id where ((dcdr_userID='" + tRealyDriver + "' and replaceDriver is not null ) or replaceDriver ='" + tRealyDriver + "' ) and dcdr_date='" + date + "';";
            str = str + "declare @tEx" + tRealyDriver + " varchar(500);";
            str = str + "select @tEx" + tRealyDriver + "= isnull(@tEx" + tRealyDriver + ", '')+ex from #t1" + tRealyDriver + " ";
            str = str + "group by ex order by ex;";
            str = str + "drop table #t1" + tRealyDriver + ";";
            // str = str + "update DriverCombineCrossingRoadPlane set miles=0 ,wHours=0,exchangeRemark=null where dcdr_date='" + date + "' and dcdr_userID='" + tRealyDriver + "';";
            str = str + "update DriverCombineCrossingRoadPlane set miles=@smilet" + tRealyDriver + " ,wHours=@shouset" + tRealyDriver + ",exchangeRemark=@tEx" + tRealyDriver + " where dcdr_date='" + date + "' and dcdr_userID='" + tRealyDriver + "';";

            return str;
        }

        public string setMonthPlaneExchangeInfoAndReplaceBySameDay(string sourceUserid, string sRealyDriver, string targetUserid, string tRealyDriver, string date, string type)
        {

            string str = " update DriverCombineCrossingRoadPlane set replaceDriver='" + sRealyDriver + "' where dcdr_userID='" + targetUserid + "' and dcdr_date='" + date + "' ;";

            str = str + setMonthPlaneExchangeInfoAndReplace(sourceUserid, sRealyDriver, targetUserid, tRealyDriver, date, "0");
            return str;

        }

        /// <summary>
        /// 设置月计划报表的替换信息和替换人员（同一天）
        /// </summary>
        /// <param name="sourceUserid"></param>
        /// <param name="targetUserid"></param>
        /// <param name="date"></param>
        //public string  setMonthPlaneExchangeInfoAndReplaceBySameDay(string sourceUserid, string targetUserid, string date)
        //{

        //        string sql = "declare @sqlmile varchar(50); declare @sqlhour varchar(50);select @sqlmile=miles,@sqlhour=wHours from DriverCombineCrossingRoadPlane where dcdr_date='" + date + "' and dcdr_userID='" + sourceUserid + "';update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+TBL.dcdr_userName+'替'+DriverCombineCrossingRoadPlane.dcdr_userName +')' ,DriverCombineCrossingRoadPlane.exchangeRemark=TBL.dcdr_userName+'替'+DriverCombineCrossingRoadPlane.dcdr_userName,wHours=CONVERT(dec(18,2),isnull(TBL.wHours,0)),miles=CONVERT(dec(18,2),ISNULL( tbl.miles, 0)),replaceDriver='" + targetUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + targetUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + sourceUserid + "';update DriverCombineCrossingRoadPlane set DriverCombineCrossingRoadPlane.dcdr_remark=DriverCombineCrossingRoadPlane.dcdr_remark+'('+TBL.dcdr_userName+'还'+DriverCombineCrossingRoadPlane.dcdr_userName +')',DriverCombineCrossingRoadPlane.exchangeRemark=TBL.dcdr_userName+'还'+DriverCombineCrossingRoadPlane.dcdr_userName ,wHours=CONVERT(dec(18,2),isnull(@sqlhour,0)),miles=CONVERT(dec(18,2),ISNULL( @sqlmile, 0)) ,replaceDriver='" + sourceUserid + "' from (select * from DriverCombineCrossingRoadPlane d where  d.dcdr_userID='" + sourceUserid + "' and d.dcdr_date='" + date + "') TBL where DriverCombineCrossingRoadPlane.dcdr_date='" + date + "' and DriverCombineCrossingRoadPlane.dcdr_userID='" + targetUserid + "';";



        //    return sql;

        //}
        public string CancelBackExchangeDriver(string souceId, string date, ref ArrayList lstSql)
        {
            return CancelBackExchangeDriver(souceId, date, ref lstSql, null);
        }


        //取消还班
        public string CancelBackExchangeDriver(string souceId, string date, ref ArrayList lstSql, string trainid)
        {
            DataTable dtSourceSwitch = GetdtSwitchedRecord(souceId, date, trainid);
            string sourCardId = souceId;
            string targetCardId = "";
            string targetDate = "";
            string souceDate = "";

            //ArrayList lstSql = new ArrayList();
            if (dtSourceSwitch.Rows.Count > 0 && dtSourceSwitch.Rows[0]["sr_appdate"].ToString() != dtSourceSwitch.Rows[0]["sr_chgdate"].ToString())
            {

                targetCardId = dtSourceSwitch.Rows[0]["sr_changer"].ToString();
                targetDate = dtSourceSwitch.Rows[0]["sr_chgdate"].ToString();
                souceDate = dtSourceSwitch.Rows[0]["sr_appdate"].ToString();
                sourCardId = dtSourceSwitch.Rows[0]["sr_applicant"].ToString();
                // bool isSetNextDayByApp = false;
                bool isSetNextDayByBack = false;
                string applyDayAppMonthID = ""; //申请当天申请司机对应的计划id
                string backToDayBackMonthID = "";//申请当天替班司机对应的计划id

                applyDayAppMonthID = dtSourceSwitch.Rows[0]["applyDayAppMonthID"].ToString();//调班的计划id

                backToDayBackMonthID = dtSourceSwitch.Rows[0]["backToDayBackMonthID"].ToString();
                DataTable dtapplyDayAppMonthID = GetCrsInfoById(applyDayAppMonthID, trainid);

                if (!string.IsNullOrEmpty(targetDate))
                {
                    DataTable dtbackToDayBackMonthID = GetCrsInfoById(backToDayBackMonthID, trainid);
                    if (targetDate == DateTime.Now.ToString("yyyy-MM-dd"))
                    {

                        CancelDriverGroupReplace(dtSourceSwitch.Rows[0][0].ToString(), backToDayBackMonthID, targetDate, dtbackToDayBackMonthID.Rows[0]["dcdr_userID"].ToString(), ref lstSql, trainid);
                    }

                    //取消申请者得班次
                    CancelReplayDriverByMonthPlane(dtSourceSwitch.Rows[0][0].ToString(), backToDayBackMonthID, targetDate, lstSql, trainid);
                    //判断是否早班 早班取消第二天的班次
                    if (dtbackToDayBackMonthID.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {
                        isSetNextDayByBack = true;

                        //获取第二天班次信息
                        DataTable dtNextCrsInfo = GetDtCrsInfo(dtbackToDayBackMonthID.Rows[0]["dcdr_userID"].ToString(), Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), trainid);

                        DataTable dtLastExchangeNexDay = GetdtLastExChangePlane(dtSourceSwitch.Rows[0][0].ToString(), dtNextCrsInfo.Rows[0][0].ToString(), Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), trainid);

                        CancelReplayDriverByMonthPlane(dtLastExchangeNexDay.Rows[0][0].ToString(), dtNextCrsInfo.Rows[0][0].ToString(), Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), lstSql, trainid);

                    }

                    lstSql.Add(setMonthPlaneInfoByDriverIDandDate(sourCardId, targetDate));
                    lstSql.Add(setMonthPlaneInfoByDriverIDandDate(targetCardId, targetDate));
                    if (isSetNextDayByBack)
                    {
                        lstSql.Add(setMonthPlaneInfoByDriverIDandDate(sourCardId, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd")));
                        lstSql.Add(setMonthPlaneInfoByDriverIDandDate(targetCardId, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd")));
                        //删除调班记录
                        string del = "delete from SwitchedRecord where parents='" + dtSourceSwitch.Rows[0][0].ToString() + "' and sr_appdate='" + Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd") + "';";
                        lstSql.Add(del);
                    }

                    //执行数据库脚本
                    lstSql.Add(UpdateSwitchedRecordWithParent(dtSourceSwitch.Rows[0][0].ToString()));

                    //如果是今天 把今天的调班记录给取消


                    //sqlHelper.ExecuteSqlTran(lstSql);
                    return "3";
                }
                return "2";



            }
            else
            {
                return "1";
            }

        }

        /// <summary>
        /// 执行sql
        /// </summary>
        /// <param name="lstSql"></param>
        public void ExecuteSqlTran(ArrayList lstSql)
        {
            sqlHelper.ExecuteSqlTran(lstSql);
        }


        public bool CancelExchangeDriverNew(string souceId, string date)
        {
            //查找调班记录
            DataTable dtSourceSwitch = GetdtSwitchedRecord(souceId, date);
            if (dtSourceSwitch.Rows.Count > 0)
            {


                string targetDate = dtSourceSwitch.Rows[0]["sr_chgdate"].ToString();
                string souceDate = dtSourceSwitch.Rows[0]["sr_appdate"].ToString();
                ArrayList lstSql = new ArrayList();
                bool res = CancelExchangeDriverNew(souceId, date, ref lstSql);
                if (res)
                {
                    //sqlHelper.ExecuteSqlTran(lstSql);
                    if (date == DateTime.Now.ToString("yyyy-MM-dd") || targetDate == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        InitCardsCollections();
                    }
                    return true;
                }
            }
            return false;
        }
        public bool CancelExchangeDriverNew(string souceId, string date, ref ArrayList lstSql, string tranId)
        {

            //获取当天最后一条调班记录
            DataTable dtSourceSwitch = GetdtSwitchedRecord(souceId, date, tranId);
            string sourCardId = souceId;
            string targetCardId = "";
            string targetDate = "";
            string souceDate = "";
            string sr_sr_SouceApplicant = "";
            string sr_SouceChanger = "";



            //string applyDayBackMonthID = "";//申请当天替班司机对应的计划id
            //string backToDayAppMonthID = "";//申请当天申请司机对应的计划id


            //ArrayList lstSql = new ArrayList();
            if (dtSourceSwitch.Rows.Count > 0)
            {

                targetCardId = dtSourceSwitch.Rows[0]["sr_changer"].ToString();
                targetDate = dtSourceSwitch.Rows[0]["sr_chgdate"].ToString();
                souceDate = dtSourceSwitch.Rows[0]["sr_appdate"].ToString();
                sourCardId = dtSourceSwitch.Rows[0]["sr_applicant"].ToString();
                sr_sr_SouceApplicant = dtSourceSwitch.Rows[0]["sr_SouceApplicant"].ToString();
                sr_SouceChanger = dtSourceSwitch.Rows[0]["sr_SouceChanger"].ToString();
                bool isSetNextDayByApp = false;
                bool isSetNextDayByBack = false;

                #region 取消调班

                //获取申请人的调班记录
                string applyDayAppMonthID = ""; //申请当天申请司机对应的计划id
                string backToDayBackMonthID = "";//申请当天替班司机对应的计划id

                // applyDayAppMonthID = dtSourceSwitch.Rows[0]["applyDayAppMonthID"].ToString();//调班的计划id

                // backToDayBackMonthID = dtSourceSwitch.Rows[0]["backToDayBackMonthID"].ToString();

                //重新获取applyDayAppMothID和backToDayBackMonthID

                DataTable dtapplyDayAppMonthID = GetCrsInfoByUseId(sr_sr_SouceApplicant, souceDate, tranId);
                applyDayAppMonthID = dtapplyDayAppMonthID.Rows[0][0].ToString();
                // DataTable dtapplyDayAppMonthID = GetCrsInfoByUseId(sr_sr_SouceApplicant, souceDate);

                // DataTable dtapplyDayAppMonthID = GetCrsInfoById(applyDayAppMonthID, tranId);

                //DataTable dtapplyDayAppMonthID = GetCrsInfo(sr_sr_SouceApplicant, souceDate);
                //if (dtapplyDayAppMonthID.Rows.Count > 0)
                //{
                //    applyDayAppMonthID = dtapplyDayAppMonthID.Rows[0][0].ToString();
                //}
                //DataTable dtbackToDayBackMonth = GetCrsInfo(sr_sr_SouceApplicant, souceDate);
                //if (dtbackToDayBackMonth.Rows.Count > 0)
                //{
                //    backToDayBackMonthID = dtbackToDayBackMonth.Rows[0][0].ToString();
                //}

                if (DateTime.Now.ToString("yyyy-MM-dd") == souceDate)
                {

                    //如果是临时调班的 那么需要去还原计划出勤时间
                    if (dtSourceSwitch.Rows[0]["is_tmp_exchange"].ToString().ToUpper() == "TRUE")
                    {
                        CancelDriverGroupAttenTime(dtSourceSwitch, ref lstSql);
                    }
                    CancelDriverGroupReplace(dtSourceSwitch.Rows[0][0].ToString(), applyDayAppMonthID, souceDate, dtapplyDayAppMonthID.Rows[0]["dcdr_userID"].ToString(), ref lstSql, tranId);

                }

                //取消申请者得班次

                CancelReplayDriverByMonthPlane(dtSourceSwitch.Rows[0][0].ToString(), applyDayAppMonthID, souceDate, lstSql, tranId);
                //判断是否早班 早班取消第二天的班次
                if (dtapplyDayAppMonthID.Rows[0]["dcdr_cls_id"].ToString() == "3")
                {
                    isSetNextDayByApp = true;
                    //获取第二天班次信息
                    DataTable dtNextCrsInfo = GetDtCrsInfo(dtapplyDayAppMonthID.Rows[0]["dcdr_userID"].ToString(), Convert.ToDateTime(souceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);

                    DataTable dtLastExchangeNexDay = GetdtLastExChangePlane(dtSourceSwitch.Rows[0][0].ToString(), dtNextCrsInfo.Rows[0][0].ToString(), Convert.ToDateTime(souceDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);

                    CancelReplayDriverByMonthPlane(dtLastExchangeNexDay.Rows[0][0].ToString(), dtNextCrsInfo.Rows[0][0].ToString(), Convert.ToDateTime(souceDate).AddDays(1).ToString("yyyy-MM-dd"), lstSql, tranId);

                }



                //更改还班是的信息

                if (!string.IsNullOrEmpty(targetDate))
                {
                    DataTable dtbackToDayBackMonthID = GetCrsInfoByUseId(sr_SouceChanger, targetDate, tranId);
                    backToDayBackMonthID = dtbackToDayBackMonthID.Rows[0][0].ToString();
                    if (targetDate == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        if (dtSourceSwitch.Rows[0]["is_tmp_exchange"].ToString().ToUpper() == "TRUE")
                        {
                            CancelDriverGroupAttenTime(dtSourceSwitch, ref lstSql);
                        }
                        CancelDriverGroupReplace(dtSourceSwitch.Rows[0][0].ToString(), backToDayBackMonthID, targetDate, dtbackToDayBackMonthID.Rows[0]["dcdr_userID"].ToString(), ref lstSql, tranId);
                    }

                    //取消申请者得班次
                    CancelReplayDriverByMonthPlane(dtSourceSwitch.Rows[0][0].ToString(), backToDayBackMonthID, targetDate, lstSql, tranId);
                    //判断是否早班 早班取消第二天的班次
                    if (dtbackToDayBackMonthID.Rows[0]["dcdr_cls_id"].ToString() == "3")
                    {
                        isSetNextDayByBack = true;

                        //获取第二天班次信息
                        DataTable dtNextCrsInfo = GetDtCrsInfo(dtbackToDayBackMonthID.Rows[0]["dcdr_userID"].ToString(), Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);

                        DataTable dtLastExchangeNexDay = GetdtLastExChangePlane(dtSourceSwitch.Rows[0][0].ToString(), dtNextCrsInfo.Rows[0][0].ToString(), Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), tranId);

                        CancelReplayDriverByMonthPlane(dtLastExchangeNexDay.Rows[0][0].ToString(), dtNextCrsInfo.Rows[0][0].ToString(), Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd"), lstSql, tranId);

                    }

                }
                //更新相对应的报表信息

                lstSql.Add(setMonthPlaneInfoByDriverIDandDate(sourCardId, souceDate));
                lstSql.Add(setMonthPlaneInfoByDriverIDandDate(targetCardId, souceDate));
                if (isSetNextDayByApp)
                {
                    lstSql.Add(setMonthPlaneInfoByDriverIDandDate(sourCardId, Convert.ToDateTime(souceDate).AddDays(1).ToString("yyyy-MM-dd")));
                    lstSql.Add(setMonthPlaneInfoByDriverIDandDate(targetCardId, Convert.ToDateTime(souceDate).AddDays(1).ToString("yyyy-MM-dd")));
                }
                if (!string.IsNullOrEmpty(targetDate))
                {
                    lstSql.Add(setMonthPlaneInfoByDriverIDandDate(sourCardId, targetDate));
                    lstSql.Add(setMonthPlaneInfoByDriverIDandDate(targetCardId, targetDate));
                    if (isSetNextDayByBack)
                    {
                        lstSql.Add(setMonthPlaneInfoByDriverIDandDate(sourCardId, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd")));
                        lstSql.Add(setMonthPlaneInfoByDriverIDandDate(targetCardId, Convert.ToDateTime(targetDate).AddDays(1).ToString("yyyy-MM-dd")));
                    }
                }


                lstSql.Add(delSwitchedRecordWithParent(dtSourceSwitch.Rows[0][0].ToString()));
                if (string.IsNullOrEmpty(tranId))
                {
                    sqlHelper.ExecuteSqlTran(lstSql);
                }
                else
                {
                    sqlHelper.ExecuteSqlTran(lstSql, tranId);
                }

                if (date == DateTime.Now.ToString("yyyy-MM-dd") || targetDate == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    InitCardsCollections(tranId);
                }
                #endregion

            }
            else
            {
                return false;
            }
            return true;

        }
        public bool CancelExchangeDriverNew(string souceId, string date, ref ArrayList lstSql)
        {
            return CancelExchangeDriverNew(souceId, date, ref lstSql, null);
        }

        /// <summary>
        /// 回滚替班人员
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="pid"></param>
        /// <param name="date"></param>
        /// <param name="uid"></param>
        /// <param name="lstSql"></param>
        public void CancelDriverGroupReplace(string sid, string pid, string date, string uid, ref ArrayList lstSql)
        {
            CancelDriverGroupReplace(sid, pid, date, uid, ref lstSql, null);
        }
        public void CancelDriverGroupReplace(string sid, string pid, string date, string uid, ref ArrayList lstSql, string tranId)
        {

            DataTable dtLastExchange = GetdtLastExChangePlane(sid, pid, date, tranId);
            if (dtLastExchange.Rows.Count > 0)
            {
                if (pid == dtLastExchange.Rows[0]["applyDayAppMonthID"].ToString())
                {


                    string updateReplace = "update DriverGroup set replaceDriver='" + dtLastExchange.Rows[0]["sr_changer"].ToString() + "' where dgrp_user_id='" + uid + "'";
                    lstSql.Add(updateReplace);
                }
                else
                {

                    string updateReplace = "update DriverGroup set replaceDriver='" + dtLastExchange.Rows[0]["sr_applicant"].ToString() + "' where dgrp_user_id='" + uid + "'";
                    lstSql.Add(updateReplace);
                }
            }
            else
            {
                string updateReplace = "update DriverGroup set replaceDriver=null where dgrp_user_id='" + uid + "'";
                lstSql.Add(updateReplace);
            }
        }
        public void CancelDriverGroupAttenTime(DataTable dtTemporarySwitch, ref ArrayList lstSql)
        {
            string updatePlanTimeSql = "update drivergroup set attentime='" + dtTemporarySwitch.Rows[0]["sr_plantime"].ToString() +
          "' where  id=" + dtTemporarySwitch.Rows[0]["sr_applicant_dgid"].ToString() + ";";
            updatePlanTimeSql = updatePlanTimeSql + "update drivergroup set attentime='" + dtTemporarySwitch.Rows[0]["tg_plantime"].ToString() +
                "' where  id=" + dtTemporarySwitch.Rows[0]["sr_changer_dgid"].ToString();
            lstSql.Add(updatePlanTimeSql);
        }
        public void CancelReplayDriverByMonthPlane(string swid, string pid, string date, ArrayList lstSql, string tranId)
        {
            DataTable dtLastExchange = GetdtLastExChangePlane(swid, pid, date, tranId);
            if (dtLastExchange.Rows.Count > 0)
            {
                // updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver='' where ID='';";
                //没有还班 所以肯定是申请者

                //判断是在还班位置还是在代班位置
                if (pid == dtLastExchange.Rows[0]["applyDayAppMonthID"].ToString())
                {

                    string updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver='" + dtLastExchange.Rows[0]["sr_changer"].ToString() + "' where ID='" + pid + "';";
                    lstSql.Add(updateReplace);
                }
                else
                {
                    string updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver='" + dtLastExchange.Rows[0]["sr_applicant"].ToString() + "' where ID='" + pid + "';";
                    lstSql.Add(updateReplace);
                }
            }

            else
            {
                string updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver=null where ID='" + pid + "';";
                lstSql.Add(updateReplace);
            }


        }
        public void CancelReplayDriverByMonthPlane(string swid, string pid, string date, ArrayList lstSql)
        {
            DataTable dtLastExchange = GetdtLastExChangePlane(swid, pid, date);
            if (dtLastExchange.Rows.Count > 0)
            {
                // updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver='' where ID='';";
                //没有还班 所以肯定是申请者

                //判断是在还班位置还是在代班位置
                if (pid == dtLastExchange.Rows[0]["applyDayAppMonthID"].ToString())
                {

                    string updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver='" + dtLastExchange.Rows[0]["sr_changer"].ToString() + "' where ID='" + pid + "';";
                    lstSql.Add(updateReplace);
                }
                else
                {
                    string updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver='" + dtLastExchange.Rows[0]["sr_applicant"].ToString() + "' where ID='" + pid + "';";
                    lstSql.Add(updateReplace);
                }
            }

            else
            {
                string updateReplace = "update DriverCombineCrossingRoadPlane set replaceDriver=null where ID='" + pid + "';";
                lstSql.Add(updateReplace);
            }


        }

        public string getReplaceDriver(string id)
        {

            if (string.IsNullOrEmpty(id))
            {
                return "NULL";
            }
            else
            {
                return id;
            }
        }

        /// <summary>
        /// 取消月报表的调班信息
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string CancelExchangeByMonthPlane(string userID, string date)
        {
            string sql = "update DriverCombineCrossingRoadPlane set exchangeRemark=null ,replaceDriver=null,miles=sourcemiles,wHours=sourcewHours where dcdr_userID='" + userID + "' and and dcdr_date='" + date + "' ;";
            return sql;
        }

        /// <summary>
        /// 设置司机信息
        /// </summary>
        /// <param name="sCard"></param>
        /// <param name="tCard"></param>
        public void setDriverCard(ref DriverCard sCard, ref DriverCard tCard, string sid, string tid)
        {
            //查找当前对应的DriverGroup
            DataTable driverDt = _teamAccess.GetDriverInfo();
            DataTable dtsid = GetCrsInfoById(sid);
            DataTable dttid = GetCrsInfoById(tid);
            string filter = "user_id =" + dtsid.Rows[0]["dcdr_userID"].ToString() + "";
            sCard = GetCardsToExchange(filter, driverDt);
            filter = "user_id  =" + dttid.Rows[0]["dcdr_userID"].ToString() + "";
            tCard = GetCardsToExchange(filter, driverDt);




        }

        private DriverCard GetCardsToExchange(string filter, DataTable dt)
        {
            ObservableCollection<DriverCard> Temp = new ObservableCollection<DriverCard>();

            DataRow[] result = dt.Select(filter);
            DriverCard card = new DriverCard();
            for (int i = 0; i < result.Length; i++)
            {


                card.Driverid = result[i]["user_id"].ToString();
                card.JobNum = result[i]["jobNum"].ToString();
                card.DriverName = result[i]["user_name"].ToString();
                card.ReplaceName = result[i]["replace_name"].ToString();
                card.DutyNum = result[i]["duty_num"].ToString();
                card.CrossNum = result[i]["cr_num"].ToString();
                card.DType = result[i]["grp_type"].ToString();
                card.Driver_group = result[i]["cls_id"].ToString();
                card.DutyNO = result[i]["dcom_NO"].ToString();
                card.ReplaceDriverId = result[i]["replaceDriver"].ToString();
                card.DriverGroupId = Convert.ToInt32(result[i]["id"]);
            }
            return card;

        }

        public string setDriverGroupByReplace(string sid, string tid, string sTempid, string tTempid)
        {
            string updateDriverGroup = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sid + "' or dgrp_user_id='" + tid + "'; ";
            updateDriverGroup = updateDriverGroup + "update DriverGroup set replaceDriver='" + sTempid + "' where dgrp_user_id='" + tid + "' and dgrp_user_id<>'" + sid + "' ;";
            updateDriverGroup = updateDriverGroup + " update DriverGroup set replaceDriver='" + tTempid + "' where dgrp_user_id='" + sid + "' and dgrp_user_id<>'" + tid + "'";
            updateDriverGroup = updateDriverGroup + " update DriverGroup set replaceDriver=null where dgrp_user_id=replaceDriver";
            return updateDriverGroup;
        }

        public string setDriverGroupByReplace(string sid, string tid)
        {
            string updateDriverGroup = "update DriverGroup set replaceDriver=NUll where dgrp_user_id='" + sid + "'; ";
            updateDriverGroup = updateDriverGroup + " update DriverGroup set replaceDriver='" + tid + "' where dgrp_user_id='" + sid + "'";
            updateDriverGroup = updateDriverGroup + " update DriverGroup set replaceDriver=null where dgrp_user_id=replaceDriver";
            return updateDriverGroup;
        }

        public DataTable GetCrsInfo(string id, string date)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where ( ( dcdr_userID='" + id + "' and replaceDriver is null) or replaceDriver='" + id + "') and dcdr_date='" + date + "'";

            DataTable dt = sqlHelper.SelectDt(str);

            return dt;
        }

        /// <summary>
        /// 替代者的交路信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public DataTable GetCrsInfoByBack(string id, string date)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where ( ( dcdr_userID='" + id + "' and replaceDriver is null) or replaceDriver='" + id + "') and dcdr_date='" + date + "'";

            DataTable dt = sqlHelper.SelectDt(str);
            if (dt.Rows.Count == 0)
            {
                str = "select * from DriverCombineCrossingRoadPlane where dcdr_userID='" + id + "' and dcdr_date='" + date + "'";
                dt = sqlHelper.SelectDt(str);
            }
            return dt;
        }



        public DataTable GetCrsInfoById(string id, string tranId)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where  ID='" + id + "'";

            DataTable dt = sqlHelper.SelectDt(str, tranId);

            return dt;
        }
        public DataTable GetCrsInfoById(string id)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where  ID='" + id + "'";

            DataTable dt = sqlHelper.SelectDt(str);

            return dt;
        }
        public DataTable GetCrsInfoByUseId(string id, string date, string tranId)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where  dcdr_userID='" + id + "' and dcdr_date='" + date + "'";

            DataTable dt = sqlHelper.SelectDt(str, tranId);

            return dt;
        }
        public DataTable GetCrsInfoByUseId(string id, string date)
        {
            string str = "select * from DriverCombineCrossingRoadPlane where  dcdr_userID='" + id + "' and dcdr_date='" + date + "'";

            DataTable dt = sqlHelper.SelectDt(str);

            return dt;
        }

        public void GetDriverInToPlane(DataTable dt, ref string sid, ref string realyid)
        {
            if (dt.Rows.Count > 0)
            {
                sid = dt.Rows[0]["dcdr_userID"].ToString();
                if (string.IsNullOrEmpty(dt.Rows[0]["replaceDriver"].ToString()))
                {
                    realyid = dt.Rows[0]["dcdr_userID"].ToString();

                }
                else
                {
                    realyid = dt.Rows[0]["replaceDriver"].ToString();
                }
            }
            else
            {
                sid = "";
                realyid = "";
            }
        }

        /// <summary>
        /// 获取最后一条调班记录
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="pid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public DataTable GetdtLastExChangePlane(string sid, string pid, string date)
        {
            return GetdtLastExChangePlane(sid, pid, date, null);
        }
        public DataTable GetdtLastExChangePlane(string sid, string pid, string date, string tranId)
        {
            string strsql = "select top 1 * from SwitchedRecord where ( ( ID<>'" + sid + "' and sr_appdate='" + date + "' and applyDayAppMonthID='" + pid + "') or (ID<>'" + sid + "' and sr_chgdate='" + date + "' and backToDayBackMonthID='" + pid + "'))  order by ID DESC";
            //and ISNULL(parents,0)<>'" + sid + "'
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql, tranId);

            return dtSwitchedRecord;
        }

        /// <summary>
        /// 判断申请者和替代者是否有调班记录
        /// </summary>
        /// <returns></returns>
        public DataTable GetSwitchRecByEideCls(string sid, string tid, string date)
        {

            string strsql = "select * from dbo.SwitchedRecord where sr_applicant='" + sid + "' and sr_changer='" + tid + "' and sr_appdate='" + date + "' and sr_chgdate <> '" + date + "'";
            //and ISNULL(parents,0)<>'" + sid + "'
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql);

            return dtSwitchedRecord;
        }

        #endregion

        /// <summary>
        /// 获取用户编号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetUserNameById(string id)
        {
            string strsql = "select * from [System_User] where user_name='" + id + "'";
            //and ISNULL(parents,0)<>'" + sid + "'
            DataTable dtSwitchedRecord = sqlHelper.SelectDt(strsql);
            if (dtSwitchedRecord.Rows.Count > 0)
            {
                return dtSwitchedRecord.Rows[0]["user_id"].ToString();
            }
            else
            {
                return "";
            }


        }

        /// <summary>
        /// 晚班退勤排序
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public DataTable SetDriverCombinWithYBSeq(DataTable dt, string startDay)
        {
            int i = 0;
            try
            {


                foreach (DataRow dr in dt.Rows)
                {
                    if (!string.IsNullOrEmpty(dr["crsAttenTime"].ToString()))
                    {
                        if (Convert.ToDateTime(dr["crsOffTime"].ToString()) < Convert.ToDateTime(dr["crsAttenTime"].ToString()))
                        {
                            //dr[4] ="1"+ drybCrossingRoad[i]["offTime"].ToString();
                            dr["crsOffTime"] = Convert.ToDateTime(startDay).AddDays(1).ToString("yyyy-MM-dd") + " " + dr["crsOffTime"].ToString();
                        }
                        else
                        {
                            dr["crsOffTime"] = startDay + " " + dr["crsOffTime"].ToString();
                        }
                        if (string.IsNullOrEmpty(dr["crsLastTrainTime"].ToString()))
                        {
                            dr["crsLastTrainTime"] = dr["crsOffTime"].ToString();
                        }

                        if (Convert.ToDateTime(dr["crsLastTrainTime"].ToString()) < Convert.ToDateTime(dr["crsAttenTime"].ToString()))
                        {
                            //dr[4] ="1"+ drybCrossingRoad[i]["offTime"].ToString();
                            dr["crsLastTrainTime"] = Convert.ToDateTime(startDay).AddDays(1).ToString("yyyy-MM-dd") + " " + dr["lastTrainTime"].ToString();
                        }
                        else
                        {
                            dr["crsLastTrainTime"] = startDay + " " + dr["crsLastTrainTime"].ToString();
                        }
                    }

                }
                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(i.ToString());

                throw;
            }
        }
        /// <summary>
        /// 获取指定日期的司机
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public DataTable GetDriverDataByTime(string datetime)
        {
            string strSql = "select * from DriverCombineCrossingRoadPlane where dcdr_date='" + datetime + "' and line=" + line + " order by dcdr_team,dcom_NO";

            return sqlHelper.SelectDt(strSql);
        }

        public DataTable GetAllDriverDataByDate(string startTime, string endTime, int userId)
        {
            string strSql = "select * from DriverCombineCrossingRoadPlane where dcdr_date between '" + startTime + "' and '" + endTime + "'  and line=" + line + " and dcdr_userid=" + userId + "";
            return sqlHelper.SelectDt(strSql);
        }



    }

    /// <summary>
    /// 班次
    /// </summary>
    public class CurrentRunningTrem
    {
        public int zb;
        public int xb;
        public int bb;
        public int yb;
    }

    public class TeamStationIndex
    {
        public int ddy = -1;
        public int rb = -1;
        public int bb = -1;
        public int scx = -1;
        public int dcx = -1;
        public List<int> ybb = new List<int>();
        public int sjz = -1;
    }

    public class SwitchedRecord
    {
        public string sr_applicant = "";
        public string sr_changer = "";
        public string sr_reason = "";
        public string sr_appdate = "";
        public string sr_appnum = "";
        public string sr_chgdate = "";
        public string sr_chgnum = "";
        public string sr_appleader = "";
        public string sr_appresult = "";
        public string st_apppby = "";
        public string st_apppbyresult = "";
        public string sr_chgleader = "";
        public string sr_chgleaderresult = "";
        public string sr_chgpby = "";
        public string sr_chgpbyresult = "";
        public string sr_approvaldate = "";
        public string parents = "";
        public string sr_plantime = "";
        public string tg_plantime = "";
        public string is_tmp_exchange = "";
        public string sr_applicant_dgid = "";
        public string sr_changer_dgid = "";
        public string applyDayAppMonthID = "";
        public string backToDayBackMonthID = "";
        public string sr_SouceApplicant = "";
        public string sr_SouceChanger = "";
    }
}
